I'm such a noob at PHP. I'm really stuck on this and could do with some help!
I'm using the following code to control if a div class and span ID appears when a variable (e.g. $project1title and $project1description) is empty/not empty.
$html = '<div class="infobar"><div class="infobar-close"></div>';
$content = false;
if ($project1title !== '' && $project1description !== '')
{
$html .= '<span id="title"></span><span id="description"></span>';
$content = true;
}
// etc.
$html .= '</div>';
if ($content)
{
echo $html;
}
The code works fine when I've only got one project title & description there but when I start adding ($project2title !== '' && $project2description !== '') if ($project3title !== '' && $project3description !== ''), etc it messes up because I need a unique ID for each project title & description. My question is, how can I make each of them have a unique ID? (Would I need to use arrays?) And once I've given each project a unique ID, where in the code above would I need to declare each unique ID?
What about this :
<?php
$projects = array(
array(
'title' => 'myTitle',
'description' => 'my description',
),
array(
'title' => 'myTitle2',
'description' => 'my description2',
),
);
$html = '<div class="infobar"><div class="infobar-close"></div>';
$content = false;
$id = 1;
foreach($projects as $project){
if(!empty($project['title']) && !empty($project['description'])){
$html .= '<span id="title'. $id .'"></span><span id="description'. $id .'"></span>';
$content = true;
}
$id++;
}
$html .= '</div>';
if ($content) {
echo $html;
}
Note that if id is important for you, you can add an id key in the projects array.
Does that help ?
Alternatively, I think you should take a look at dynamic vars :
here is simple example of what you can do with them :
<?php
$html = '<div class="infobar"><div class="infobar-close"></div>';
$content = false;
for($i = 1;$i<=10;$i++){
$title = 'project' . $i . 'title';
$description = 'project' . $i . 'description';
if (isset($$title) && isset($$description) && $$title !== '' && $$description !== '')
{
$html .= '<span id="title'. $i .'"></span><span id="description'. $i .'"></span>';
$content = true;
}
}
$html .= '</div>';
if ($content)
{
echo $html;
}
Shouldn't the operations be:
!=
instead of
!==
?
Related
I have been looking for a solution and couldn't find.
I have created a shortcode that displays social link depends on type with folowing code:
function ns_social_buttons_dynamic($atts,$content,$tag) {
$facebookUrl = get_option('ns-company-facebook');
$messengerUrl = get_option('ns-company-messenger');
if (!empty($facebookUrl)) {
$fb = '<a class="btn-ns btn-ns-second m-1 bg-facebook" href="https://facebook.com/'.$facebookUrl.'" role="button" target="blank"><i class="fab fa-facebook-f"></i></a>';
};
if (!empty($messengerUrl)) {
$msngr = '<a class="btn-ns btn-ns-second m-1 bg-messenger" href="https://m.me/'.$messengerUrl.'" role="button" target="blank"><i class="fab fa-facebook-messenger"></i></a>';
}
$nsSocial = $fb . $msngr;
//get admin url
$addLink = get_site_url( $blog_id, 'wp-admin/', $scheme );
//default value of shortcodes shows all social buttons
$values = shortcode_atts(array(
'type' => 'all',
'output' => 'raw',
),$atts);
//social button based on type
$output = '';
if($values['type'] == 'all' and !empty($nsSocial)){
$output = $nsSocial;
}
else if($values['type'] == 'facebook' and !empty($facebookUrl)){
$output = $fb;
}
else if($values['type'] == 'messenger' and !empty($messengerUrl)){
$output = $msngr;
}
else {
$output = 'field is empty <a href=' . $addLink . 'admin.php?page=ns-settings' .' >add username</a>';
}
return $output;
}
add_shortcode( 'ns-social', 'ns_social_buttons_dynamic' );
This code works just fine e.g [ns-socia type='facebook'] will output the right button.
now what I need is if the shortcode like following [ns-socia type='facebook' output='raw'] to show only the url and not the button.
I tried following:
//social button based on type
$output = '';
if($values['type'] == 'all' and !empty($nsSocial)){
$output = $nsSocial;
}
else if($values['type'] == 'facebook' and $values['output'] == 'raw' and !empty($facebookUrl)){
$output = $facebookUrl;
}
else if($values['type'] == 'messenger' and $values['output'] == 'raw' and !empty($messengerUrl)){
$output = $messengerUrl;
}
else {
$output = 'field is empty <a href=' . $addLink . 'admin.php?page=ns-settings' .' >add username</a>';
}
return $output;
I am not sure i am doing it right with the conditional php conditional statements...
I have to extend an existing menu to a multilevel one. I am having a hard time wrapping my head around it so I'm hoping somebody can help me out.
First I've added another table in the database with the name parent_id.
Then I'd like to see if this column is filled out, so greater than > 0.
And then of course, check to see if id == parent_id.
If so, I'd like to display my submenu on hover of the parent item.
My current menu is a multi lang menu.
This is my current model:
var $default_order_by = array('position');
function findView($page)
{
$language = $this->config->item('language');
$p = new Page();
$p->where('url_' . $language, $page)->get();
return $p->view;
}
function findPageMenu($page)
{
$language = $this->config->item('language');
$p = new Page();
$p->where('url_' . $language, $page)->get();
return $p->menu;
}
function findAllByView()
{
$pages = new Page();
$result = array();
foreach ($pages->get() as $page)
$result[$page->view] = $page;
return $result;
}
function getMenu()
{
$pages = new Page();
if ($this->session->userdata('is_admin'))
return $pages->where('position >', 0)->get();
else
return $pages->where('position >', 0)->where('admin', 0)->get();
}
function getUrlByView($view)
{
$page = new Page();
$page->where('view', $view)->get();
$language = $this->config->item('language');
return $page->{'url_' . $language};
}
And this is my view:
<ul class="primary-nav">
<?php foreach($menu as $page): ?>
<li class="primary-nav__item">
<a class="primary-nav__link" <?php if ($page_menu == $page->view): ?>class="active" <?php endif; ?>href="<?php echo base_url() . $this->config->item('language_abbr') . '/' . $page->{'url_' . $this->config->item('language')}; ?>">
<?php echo mb_strtoupper($page->{'title_' . $this->config->item('language')}, 'UTF-8'); ?>
</a>
</li>
<?php endforeach; ?>
I was thinking of doing something like this:
function getSubMenu()
{
if ($this->session->userdata('is_admin'))
return $pages->where('position >', 0 && 'parent_id >', 0)->get();
else
// return $pages->where('position >', 0 && 'parent_id >', 0)->get();
echo '<h1> yay </h1>';
}
(ignore the yay, lol) But this obviously doesn't even begin to cut it.
Suggestion: You can add the "parent_id" in the same table. If there is a parent then fill it with parent id or with 0.
Answer: Get your data as a one dimentional array with all the rows with parent id. Then use the below function to create a multi dimensional array with parent and child.
function formatTree($tree, $parent = NULL) {
$treeArray = array();
foreach ($tree as $item) {
if ($item['menu_parent'] == 0) {
$treeArray[$item['menu_id']] = $item;
}
else {
$treeArray[$item['menu_parent']]['sub'][] = $item;
}
}
return $treeArray;
}
Now use the below function to make an intended ul-li list of parent-child menu
function buildMenu($menu_array, $is_sub = FALSE) {
$attr = (!$is_sub) ? ' class="sidebar-menu"' : ' class="treeview-menu"';
$menu = "<ul>"; // Open the menu container
foreach ($menu_array as $id => $properties) {
if (!isset($properties['sub'])) {
$is_sub = TRUE;
}
elseif (empty($properties['sub'])) {
$is_sub = TRUE;
}
foreach ($properties as $key => $val) {
if (is_array($val) && !empty($val)) {
$sub = $this -> buildMenu($val, TRUE);
}
else {
$sub = NULL;
$$key = $val;
}
}
if ($properties['menu_url']) {
$url = $properties['menu_url'];
}
$menu .= "<li>" . $menu_name . "</li>";
unset($url, $menu_name, $sub);
}
return $menu . "</ul>";
}
I am using this in my application. The array structure of menu data should be
array(
[0] => array(
'menu_name' => 'name',
'menu_url' => 'url',
'menu_id' => 'id',
'menu_parent' => 'parent id'
),
[1] => array(
'menu_name' => 'name',
'menu_url' => 'url',
'menu_id' => 'id',
'menu_parent' => 'parent id'
)
)
I am building out a nested menu for a Magento store I am working on. The store has around 700 categories in total (that are nested around 4 levels at most) that need to be spat out into this menu.
The code I have written takes on average 2.5s to process (tested using microtime).
I am wondering if this is unavoidable given the amount of categories that need to be processed.
Anyways, this is the code I have come up with (go easy I am a front end dev by trade): NOTE: is am also using this code to loop out CMS pages in the same fashion
$type = Mage::registry('current_category') ? 'category' : 'page';
if($type == 'category') {
$currentID = Mage::registry('current_category')->getId();
$parentIDs = explode('/', Mage::registry('current_category')->path);
$rootID = Mage::app()->getStore()->getRootCategoryId();
}
else {
$currentID = Mage::getSingleton('cms/page')->getId();
$parentIDs = Mage::getSingleton('cms/page')->getPathIds();
$rootID = 0;
}
function checkChildHtml($parentId, $htmlString) {
$string = '';
if($parentId != $rootID) {
$string = $htmlString;
}
return $string;
}
// Recurse the site tree and build out a menu
function buildChildMenu($type, $currentID, $parentId, $isChild, $parentIDs, $rootID) {
// Get the appropriate collection based on type
if($type == 'category') {
$children = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active', '1')
->addAttributeToFilter('include_in_menu', '1')
->addAttributeToFilter('parent_id', array('eq' => $parentId))
->addAttributeToSort('position', 'asc');
}
else {
$children = Mage::getModel('cms/page')->getCollection()
->addFieldToSelect('*')
->addFieldToFilter('is_active', '1')
->addFieldToFilter('include_in_menu', '1')
->addFieldToFilter('parent_id', array('eq' => $parentId))
->setOrder('position','asc');
}
// TODO check for $parentID != $rootID is a little hacky, need to DRY this up
$html .= ($parentId != $rootID) ? '<ul>' : null;
// Loop over categories at the current level
foreach($children as $child) {
$childId = $child->getId();
$parent = (count($child->getChildren()) > 0) ? $child->getChildren() : false;
$classes = [];
// Build out class lists
if($parent) {
$classes[] = 'parent';
}
if(in_array($childId, $parentIDs, true) || count($children) == 1) {
$classes[] = "current active";
}
if($childId == $currentID) {
$classes[] = "current-page";
}
// Build out the list item with the values appropriate to the type
if($type == 'category') {
$html .= checkChildHtml($parentId, '<li class="' . implode(' ', $classes) . '">' . ($parent ? '<button class="toggle"></button>' : null) . '' . $child->getName() . '');
}
else {
$html .= checkChildHtml($parentId, '<li class="' . implode(' ', $classes) . '">' . ($parent ? '<button class="toggle"></button>' : null) . '' . $child->title . '');
}
// Append the list html (if not root page)
if($parent) {
// Get the categories below this page
$html .= buildChildMenu($type, $currentID, $child->getId(), true, $parentIDs, $rootID);
}
// Close the list (if not root product page)
$html .= checkChildHtml($parentId, '</li>');
}
$html .= checkChildHtml($parentId, '</ul>');
return $html;
}
// Build out menu from root level down
$categoryListHtml = buildChildMenu($type, $currentID, $rootID, false, $parentIDs, $rootID);
Are there any obvious bottlenecks here? If not, what is best practise in this scenario?
For instance, should I AJAX the children when requested? Or maybe cache the menu? Or... something else?
Okay, the issue was that I had my cache turned off whilst I was developing this menu. With the cache enabled the processing time is insignificant.
I'm trying to implement a function to be able to add directional (up / down) icons next to each of the table headers for a pagination table within CakePHP.
My current code is as follows:
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
$type_opposite = ($type === 'asc' ? 'down' : 'up');
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
}
else
{
$icon = " <i class='fa fa-angle-" . $type_opposite . "'></i>";
}
return "'$key', '$title' " . "$icon";
}
Which I am calling on the page as (on each of the table header fields):
<?php echo $this->Paginator->sort(sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>
This produces the following error:
Notice (8): Array to string conversion [CORE/Cake/View/Helper/HtmlHelper.php, line 372]
I think I am quite close to what I need, I just cannot figure out what I am returning incorrectly from the function to get this to work.
Thanks
Inspired by your solution I have created a Helper extending PaginatorHelper to solve the problem.
Here is the code of file name MyPaginatorHelper.php:
<?php
namespace App\View\Helper;
use Cake\View\Helper\PaginatorHelper;
use Cake\Utility\Inflector;
class MyPaginatorHelper extends PaginatorHelper
{
public function sort($key, $title = null, array $options = [])
{
if (empty($title)) {
$title = $key;
if (strpos($title, '.') !== false) {
$title = str_replace('.', ' ', $title);
}
$title = __(Inflector::humanize(preg_replace('/_id$/', '', $title)));
}
$sortKey = $this->sortKey();
if (strpos($sortKey, '.') !== false) {
$sortKey = substr($sortKey, strpos($sortKey, '.')+1);
}
$sortDir = $this->sortDir() === 'asc' ? 'up' : 'down';
if($key == $sortKey)
{
$title .= " <i class='fa fa-angle-" . $sortDir . "'></i>";
$options['escape'] = false;
}
return parent::sort($key, $title, $options);
}
}
To use this helper you have to add this line in the AppView::initialize() method:
$this->loadHelper('Paginator', ['className' => 'MyPaginator']);
And then all the Paginator->sort() calls will have this feature by default.
I ended up coming up with a solution however I don't know if it is the best way around it. It does work however.
<?php
$sort_key = $this->Paginator->sortKey();
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
function sortArrows($key, $title, $sort_key, $type)
{
if($key == $sort_key)
{
$icon = " <i class='fa fa-angle-" . $type . "'></i>";
return $title . " " . $icon;
}
else
{
return $title;
}
}
?>
Called like:
<?php echo $this->Paginator->sort('street_suburb', sortArrows('street_suburb', 'Suburb', $sort_key, $type), array('escape' => false)); ?>
I am having problem with calling a function from another plugin it seems to return nothing tho this does work on other plugin
function caller_func()
{
if (!function_exists('form')) return;
return form($number = null);
}
function chrp1_get_popup(){
$chrp1_popup = '<div id="fullscre"></div>';
$chrp1__query= "post_type=popup-widget-details&showposts=1";
query_posts($chrp1__query);
if (have_posts()) : the_post();
$chrp1_mykey_values = get_post_custom_values('code');
$chrp1_descrip = get_the_content();
$chrp1_popup .= '<span onclick="chrp1_showall();">'.$chrp1_descrip.'</span>';
$chrp1_popup .= '<div id="newsox">';
$chrp1_popup .= '<img src="'.chrp1_PATH.'image/cross.png" class="ccross"
onclick="chrp1_getrid();" width="23"/>';
$getfunc = 'caller_func';
$chrp1_popup .= $getfunc();
$chrp1_popup .= '</div>';
endif; wp_reset_query();
return $chrp1_popup;
}
this code works on my other plugins I want to call but not this one below can anybody help
function form($number = null) {
if ($number == null)
return $this->subscription_form();
$options = get_option('newsletter_forms');
$form = $options['form_' . $number];
if (stripos($form, '<form') !== false) {
$form = str_replace('{newsletter_url}', plugins_url('newsletter/do/subscribe.php'), $form);
} else {
$form = '<form method="post" action="' . plugins_url('newsletter/do/subscribe.php') . '" onsubmit="return newsletter_check(this)">' .
$form . '</form>';
}
$form = $this->replace_lists($form);
return $form;
}
when I check the source code nothing from the form has loaded