PHP breadcrumb array, link is not full - php

I go the following code for breadcrumb :
<?php
class Breadcrumb
{
private $breadcrumb;
private $separator = ' / ';
private $domain = 'example.org';
public function build($array)
{
$breadcrumbs = array_merge(array('Home' => ''), $array);
$count = 0;
foreach($breadcrumbs as $title => $link) {
$this->breadcrumb .= '
<span itemscope="" itemtype="https://schema.org/BreadcrumbList">
<a href="'.$this->domain. '/'.$link.'" itemprop="url">
<span itemprop="title">'.$title.'</span>
</a>
</span>';
$count++;
if($count !== count($breadcrumbs)) {
$this->breadcrumb .= $this->separator;
}
}
return $this->breadcrumb;
}
}
?>
I call it as follow:
<?php
$breadcrumb = new Breadcrumb();
echo $breadcrumb->build(array(
$pageTitle => 'about',
'More' => 'more.php'
));
?>
pageTitle is a var on top of each page.
The output is correct and shows: Home / About / More
but, the link on each one of them is as follow:
Home: example.org
About: example.org/about
More: example.org/more.php
And I am looking for output like that: example.org/about/more.php
Thank you very much!

You can concatenate the links as you progress through your loop...
$bclink = '';
foreach($breadcrumbs as $title => $link) {
if ($link != '') {
$bclink .= '/' . $link;
}
$this->breadcrumb .= '
<span itemscope="" itemtype="https://schema.org/BreadcrumbList">
<a href="'.$this->domain.$bclink.'" itemprop="url">
<span itemprop="title">'.$title.'</span>
</a>
</span>';
$count++;
if($count !== count($breadcrumbs)) {
$this->breadcrumb .= $this->separator;
}
}

Related

how use enclosing shortcodes in php ( wordpress theme )

edd restrict content plugin creates this shortcodes and these are working in pages and posts :
[edd_restrict id="any"]sample restricted html or text[/edd_restrict]
but i want to use it in my theme not in the posts or pages.
i tried this :
<?php =echo do_shortcode( '[edd_restrict id="any"]' . sample text . '[/edd_restrict]' );?>
but theme shows me fatal error.
so how can i use this shortcodes in wordress theme?
sample text here will be a php code that i want to restrict.
let me tell you more... i want to put the line below between those shortcodes in my single.php in wordpress :
<li><?php if(get_post_meta($post->ID, 'download',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download',true)."' > دانلود با لینک مستقیم</a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download32',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download32',true)."'>لینک مستقیم نسخه 32bit / </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download64',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download64',true)."'>لینک مستقیم نسخه 64bit </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'downloadwin',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'downloadwin',true)."'>دانلود نسخه ویندوز </a> ";} else { echo ""; } ?></li>
The method do_shortcode accepts a string of a shortcode and it's attributes/content. So for example
<?php
$string = "some value or <b>html</b>";
// or (?)
$string = include TEMPLATEPATH . "/post-ads.php";
// or (!)
ob_start();
include TEMPLATEPATH . "/post-ads.php";
$string = ob_get_clean();
// for a specific use case:
if (get_post_meta($post->ID, 'download', true) != "") {
$string = "<a href='" . get_post_meta($post->ID, 'download', true) . "' >download</a> ";
} else {
$string = "";
}
if (get_post_meta($post->ID, 'download32', true) != "") {
$string2 = "<a href='" . get_post_meta($post->ID, 'download32', true) . "'>download 32bit / </a> ";
} else {
$string2 = "";
}
// after you have string:
echo do_shortcode('[edd_restrict id="any"]' . $string . '[/edd_restrict]');

php: Generate dynamic menu with CSS code from multidimensional array

I'm trying to mark the current requested page as active in my menu but something seems to go wrong... Me and my co-workers can't figure out what's going wrong... I've been trying to figure this one out for more than a week now, I've read what feels like dozens of questions and answers on this and other sites to no avail.
The one thing that really puzzles me is how the value of $page seems to change from a string to a number as you can tell with the debugging I've implemented.
This is the relevant code from index.php:
$pages = array('home','overons','onsteam','organisatie','diensten','aandeslag',
'ictlab','eendagbij','opdrachtgevers','verwijzers',
'trajectbegeleiding','contact');
if(in_array($_GET['p'], $pages)) {
$content = $_GET['p'];
} else {
$content = "home";
}
echo "<!-- content = ".$content." -->\n";
require($inc_path.'navbar'.$php_ext);
and the code from navbar.php:
$menu = array (
'home',
'overons' => array (
'onsteam',
'organisatie'
),
'diensten' => array (
'aandeslag',
'ictlab',
'eendagbij'
),
'opdrachtgevers',
'verwijzers' => array (
'trajectbegeleiding'
),
'contact'
);
$pagenames = array (
'home' => 'Home',
'overons' => 'Over Ons',
'onsteam' => 'Ons Team',
'organisatie' => 'Organisatie',
'diensten' => 'Diensten',
'aandeslag' => 'Aan De Slag',
'ictlab' => 'ICT Lab',
'eendagbij' => 'Een dag bij',
'opdrachtgevers' => 'Opdrachtgevers',
'verwijzers' => 'Verwijzers',
'trajectbegeleiding' => 'Traject begeleiding',
'contact' => 'Contact'
);
function MakeMenu($menu, $currentpage, $level = 0) {
echo "<!-- MakeMenu0: currentpage = ".$currentpage." -->\n";
global $pagenames;
$ret = "";
$indent = str_repeat(" ", $level * 2);
if ($level!=0) {
$ret .= "<!-- MakeMenu1: Level = ".$level." -->\n";
$ret .= sprintf("%s<ul class=\"dropdown-menu\">\n", $indent);
} else {
$ret .= "<!-- MakeMenu2: Level = 0 -->\n";
$ret .= sprintf("%s<ul class=\"nav navbar-nav\">\n", $indent);
}
$indent = str_repeat(" ", ++$level * 2);
foreach ($menu as $page => $subpages) {
if (!is_numeric($page)) {
if ($page==$currentpage) {
$ret .= "<!-- MakeMenu3: page (".$page.") = currentpage (".$currentpage.") -->\n";
if (is_array($subpages)) {
$ret .= sprintf("%s<li class=\"active dropdowm\"><a href='?p=%s'>%s<span class='caret'></span></a>", $indent, $page, $pagenames[$page]);
} else {
$ret .= sprintf("%s<li class=\"active\"><a href='?p=%s'>%s</a>", $indent, $page, $pagenames[$page]);
}
} else {
$ret .= "<!-- MakeMenu4: page (".$page.") != currentpage (".$currentpage.") -->\n";
if (is_array($subpages)) {
$ret .= sprintf("%s<li class=\"dropdown\"><a href='?p=%s'>%s<span class='caret'></span></a>", $indent, $page, $pagenames[$page]);
} else {
$ret .= sprintf("%s<li><a href='?p=%s'>%s</a>", $indent, $page, $pagenames[$page]);
}
}
}
if (is_array($subpages)) {
$ret .= "\n";
$ret .= MakeMenu($subpages, $currentpage, $level + 1);
$ret .= $indent;
} else if (strcmp($page, $subpages)) {
if ($page==$currentpage){
$ret .= "<!-- MakeMenu5: page (".$page.") = currentpage (".$currentpage.") -->\n";
$ret .= sprintf("%s<li class=\"active\"><a href='?p=%s'>%s</a>", $indent, $subpages, $pagenames[$subpages]);
} else {
$ret .= "<!-- MakeMenu6: page (".$page.") != currentpage (".$currentpage.") -->\n";
$ret .= sprintf("%s<li><a href='?p=%s'>%s</a>", $indent, $subpages, $pagenames[$subpages]);
}
}
$ret .= sprintf("</li>\n", $indent);
}
$indent = str_repeat(" ", --$level * 2);
$ret .= sprintf("%s</ul>\n", $indent);
return($ret);
}
echo MakeMenu($menu, $content);
And the very puzzeling output:
<!-- MakeMenu0: currentpage = overons -->
<!-- MakeMenu0: currentpage = overons -->
<!-- MakeMenu0: currentpage = overons -->
<!-- MakeMenu0: currentpage = overons -->
<!-- MakeMenu2: Level = 0 -->
<ul class="nav navbar-nav">
<!-- MakeMenu5: page (0) = currentpage (overons) -->
<li class="active"><a href='?p=home'>Home</a></li>
<!-- MakeMenu3: page (overons) = currentpage (overons) -->
<li class="active dropdowm"><a href='?p=overons'>Over Ons<span class='caret'></span></a>
<!-- MakeMenu1: Level = 2 -->
<ul class="dropdown-menu">
<!-- MakeMenu5: page (0) = currentpage (overons) -->
<li class="active"><a href='?p=onsteam'>Ons Team</a></li>
<!-- MakeMenu6: page (1) != currentpage (overons) -->
<li><a href='?p=organisatie'>Organisatie</a></li>
</ul>
</li>
<!-- MakeMenu4: page (diensten) != currentpage (overons) -->
<li class="dropdown"><a href='?p=diensten'>Diensten<span class='caret'></span></a>
<!-- MakeMenu1: Level = 2 -->
<ul class="dropdown-menu">
<!-- MakeMenu5: page (0) = currentpage (overons) -->
<li class="active"><a href='?p=aandeslag'>Aan De Slag</a></li>
<!-- MakeMenu6: page (1) != currentpage (overons) -->
<li><a href='?p=ictlab'>ICT Lab</a></li>
<!-- MakeMenu6: page (2) != currentpage (overons) -->
<li><a href='?p=eendagbij'>Een dag bij</a></li>
</ul>
</li>
<!-- MakeMenu6: page (1) != currentpage (overons) -->
<li><a href='?p=opdrachtgevers'>Opdrachtgevers</a></li>
<!-- MakeMenu4: page (verwijzers) != currentpage (overons) -->
<li class="dropdown"><a href='?p=verwijzers'>Verwijzers<span class='caret'></span></a>
<!-- MakeMenu1: Level = 2 -->
<ul class="dropdown-menu">
<!-- MakeMenu5: page (0) = currentpage (overons) -->
<li class="active"><a href='?p=trajectbegeleiding'>Traject begeleiding</a></li>
</ul>
</li>
<!-- MakeMenu6: page (2) != currentpage (overons) -->
<li><a href='?p=contact'>Contact</a></li>
</ul>
Well regarding puzzling behavior:
The one thing that really puzzles me is how the value of $page seems
to change from a string to a number as you can tell with the debugging
I've implemented.
If you look closely at this line:
foreach ($menu as $page => $subpages) {
you will see that key of an array is assigned to $page. From your array:
$menu = array (
'home',
'overons' => array(
'onsteam',
'organisatie'
),
'diensten' => array(
'aandeslag',
'ictlab',
'eendagbij'
),
'opdrachtgevers',
'verwijzers' => array(
'trajectbegeleiding'
),
'contact'
);
we can see that some of pages are keys, and some are values. That is why you have sometimes pages names and sometimes array indexes.
You can define your array as following to prevent this behavior:
$menu = [
'home' => null,
'overons' => [
'onsteam' => null,
'organisatie' => null
],
'diensten' => [
'aandeslag' => null,
'ictlab' => null,
'eendagbij' => null
],
'opdrachtgevers' => null,
'verwijzers' => [
'trajectbegeleiding' => null
],
'contact' => null
];
Going further you have a really complicated recursive function. I would suggest using PHP Iterators. In particular RecursiveArrayIterator alongside with RecursiveIteratorIterator, that can be extended like this:
class UlRecursiveIteratorIterator extends RecursiveIteratorIterator
{
public function beginIteration()
{
echo '<ul class="nav navbar-nav">', PHP_EOL;
}
public function endIteration()
{
echo '</ul>', PHP_EOL;
}
public function beginChildren()
{
echo str_repeat(' ', $this->getDepth() + 1), '<ul class="dropdown-menu">', PHP_EOL;
}
public function endChildren()
{
echo str_repeat(' ', $this->getDepth() + 1), '</ul>', PHP_EOL;
echo str_repeat(' ', $this->getDepth()), '</li>', PHP_EOL;
}
}
Having this iterator, your function can be refactored to one simple foreach loop:
$iterator = new RecursiveArrayIterator($menu);
$iterator = new UlRecursiveIteratorIterator(
$iterator,
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $page => $_) {
$active = false;
// Used for pritty print only. Remove in production.
$depth = $iterator->getDepth();
$line = str_repeat(' ', ($depth + 1) + ($depth === 0 ? 0 : 1));
if ($page === $content) {
$active = true;
}
$class = $active ? 'active' : '';
if ($iterator->callHasChildren()) {
$line .= "<li class=\"$class dropdown\"><a href='?p=$page'>{$pagenames[$page]}<span class='caret'></span></a>";
} else {
$line .= "<li class=\"$class\"><a href='?p=$page'>{$pagenames[$page]}</a>";
}
echo $line, PHP_EOL;
}
Here is the demo.

How to set "class = active" for second tab?

I have some tabs. In that sometimes first tab is "introduction" and sometimes "outline" is first tab. I have set introduction class=active when it comes first. But when outline comes first I am not getting how to set its class as active.
code is like below
<ul class="nav-tabs" role="tablist">
<?php
$tabs = array();
if(!$sessId == "" && !$checkcourse){
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>true, "comment"=>true);
} else if($sessId == "") {
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>false, "comment"=>true);
} else {
$tabs = array("introduction"=>false, "outline"=>true,"announcement"=>true,"discussion"=>true,"review"=>true, "student"=>true, "comment"=>false);
}
?>
<?php if($tabs['introduction']) { ?>
<li class="active">Introduction</li>
<?php } ?>
<?php if($tabs['outline']) { ?>
<li>Outline</li>
<?php } ?>
<?php if($tabs['review']) { ?>
<li>Review</li>
<?php } ?>
<?php if($tabs['student']) { ?>
<li>Student</li>
<?php } ?>
<?php if($tabs['comment']) { ?>
<li>Comment</li>
<?php } ?>
<?php if($tabs['announcement']) { ?>
<li>Announcement</li>
<?php } ?>
<?php if($tabs['discussion']) { ?>
<li>Discussion</li>
<?php } ?>
</ul>
Simple check with ternary operator is:
<?php if($tabs['outline']) {?>
<li <?=$tabs['introduction']? '' : ' class="active"';?>>Outline</li>
<?php } ?>
So you check if $tabs['introduction'] isset then you don't need class="active", else - add this class.
Update:
But as first item of tab can change, I advise to create simple foreach:
$is_first = true;
foreach ($tabs as $tab_name => $value) {
if ($value) {
echo '<li' . ($is_first? ' class="active"' : '') . '>' . $tab_name . '</li>';
$is_first = false; // fix that we have first value here
}
}
Here your main problem is how to link href value and caption.

Hierarchical tree menu - PHP / MySQL

In working on a dynamic menu w/ CRUD I have been having some trouble with the finishing touches. It works, but there are some extra tags getting inserted where there shouldn't be and can't figure out how to clean it up before I share it with the world. I used this as a starting point, then changed it to work with an accordion menu (http://www.phpro.org/tutorials/Simple-Mysql-PHP-Menu.html).
Below is the data from the table (I changed the names on the first 2 fields to get it to fit in the SO format from menu_item_id to id, and from menu_parent_id to pid).
id pid menu_item_name menu_url sortorder status
1 0 Settings 0 ACTIVE
2 5 Grid Demo grid.php ACTIVE
3 5 setGridOptions gridoptions.php ACTIVE
4 1 Menu Items adminmenu.php 1 ACTIVE
5 0 Grid Settings 100 ACTIVE
6 1 General Settings settings.php 100 ACTIVE
Here is the PHP that connects to the mysql database and creates the hierarchical tree array to make it work:
include 'db.php';
$sql = "SELECT * FROM menu_items WHERE status = \"ACTIVE\" ORDER BY sortorder, menu_item_name";
$query = $db->query($sql);
while($data = $query->fetch(PDO::FETCH_ASSOC))
// loop over the results
{
// Assign by reference
$thisref = &$refs[ $data['menu_item_id'] ];
// add the the menu parent
$thisref['menu_item_id'] = $data['menu_item_id'];
$thisref['menu_parent_id'] = $data['menu_parent_id'];
$thisref['menu_item_name'] = $data['menu_item_name'];
$thisref['menu_url'] = $data['menu_url'];
// if there is no parent id
if ($data['menu_parent_id'] == 0)
{
$list[ $data['menu_item_id'] ] = &$thisref;
}
else
{
$refs[ $data['menu_parent_id'] ]['children'][ $data['menu_item_id'] ] = &$thisref;
}
}
function create_list( $arr )
{
$html = "";
foreach ($arr as $key=>$v)
{
if ($v['menu_parent_id'] == '0')
{
$html .= '<a class="menuitem submenuheader" href="'. $v['menu_url'] .'">'.$v['menu_item_name']."</a>\n";
$html .= "<div class=\"submenu\">\n<ul>\n";
$html .= "<li>" . create_list($v['children']) . "</li>";
$html .= "</ul>\n";
}
else{
$html .= '<li><a id="' . $v['menu_item_id'] . '">'.$v['menu_item_name']."</a></li>\n";
}
}
$html .= "</div>\n";
return $html;
}
echo "<div class=\"glossymenu\">";
echo create_list( $list );
echo "</div>";
When I run it, it outputs the following:
<div class="glossymenu"><a class="menuitem submenuheader">Settings</a>
<div class="submenu">
<ul>
<li><li><a id="4">Menu Items</a></li>
<li><a id="6">General Settings</a></li>
</div>
</li></ul>
<a class="menuitem submenuheader" href="">Grid Settings</a>
<div class="submenu">
<ul>
<li><li><a id="2">Grid Demo</a></li>
<li><a id="3">setGridOptions</a></li>
</div>
</li></ul>
</div>
</div>
As you can see there are extra <li> tags, the </ul> is in the wrong
spot (should be after the </div>) Other than that, it is working great.
The other thing I can't figure out is if I have a root menu item with no children, I would love it to have a different output like
<a id="8">No Children Menu Item</a>
Instead of:
<a class="menuitem submenuheader">No Children Menu Item</a>
The second example would create the make it show up the little (+/-) for expanding and contracting and wouldn't allow me to click on it. For clarification on the <a> tags, I am using javascript to do a .get() based off the id which is why there is no href or url shown.
UPDATE
It is working correctly and I posted it on Github for anyone that wants it.
https://github.com/ajhalls/php-accordian-menu
Try this :
<?php
include 'db.php';
$sql = "SELECT * FROM menu_items WHERE status = 'ACTIVE' ORDER BY pid ASC, sortorder ASC, menu_item_name ASC";
$query = $db->query($sql);
$menu_items = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)) {
if($data['pid'] == 0) {
$menu_items[$data['id']] = array();
$menu_items[$data['id']]['id'] = $data['id'];
$menu_items[$data['id']]['name'] = $data['menu_item_name'];
$menu_items[$data['id']]['url'] = $data['menu_url'];
$menu_items[$data['id']]['children'] = array();
} else if($data['pid'] != 0) {
$tmp = array();
$tmp['id'] = $data['id'];
$tmp['name'] = $data['menu_item_name'];
$tmp['url'] = $data['menu_url'];
array_push($menu_items[$data['pid']]['children'],$tmp);
unset($tmp);
}
}
function create_list($arr)
{
$html = "";
foreach($arr as $key => $value) {
if(count($value['children']) > 0) {
$html .= ' <a class="menuitem submenuheader" href="'. $value['url'] .'">'.$value['name'].'</a>
<div class="submenu">
<ul>';
foreach($value['children'] AS $child) {
$html .= ' <li>
<a id="'.$child['id'].'">'.$child['name'].'</a>
</li>';
}
$html .= ' </ul>
</div>';
} else{
$html .= ' <a id="'.$value['id'].'">'.$value['name'].'</a>';
}
}
return $html;
}
echo "<div class=\"glossymenu\">";
echo create_list($menu_items);
echo "</div>";
?>

PHP Dynamic Count & Limit Menu items

I want to modify this code which works pretty good but (or I don't know because I'm new with php) I can't limit the number of li's displayed for the main elements in the menu. The actual code will echo all elements it finds, I want to limit the times
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
this line is echoed.. let's say to echo just the first 15 elements + a "MORE" button under which to display the rest of the elements as sub-menus.. (this is a 2 level horizontal menu). Can someone please help me? I really tried a lot but I'm not an expert in PHP..
Thanks!
<?php
require_once( '../../../inc/header.inc.php' );
require_once( DIRECTORY_PATH_INC . 'membership_levels.inc.php' );
require_once( DIRECTORY_PATH_ROOT . "templates/tmpl_{$tmpl}/scripts/TemplMenu.php" );
class SimpleMenu extends TemplMenu
{
function getCode()
{
$this->iElementsCntInLine = 100;
$this->getMenuInfo();
$this->genTopItems();
return $this->sCode;
}
function genTopItem($sText, $sLink, $sTarget, $sOnclick, $bActive, $iItemID, $isBold = false, $sPicture = '')
{
$sActiveStyle = ($bActive) ? ' id="tm_active"' : '';
if (!$bActive) {
$sAlt= $sOnclick ? ( ' alt="' . $sOnclick . '"' ) : '';
$sTarget = $sTarget ? ( ' target="_parent"' ) : '';
}
$sLink = (strpos($sLink, 'http://') === false && !strlen($sOnclick)) ? $this->sSiteUrl . $sLink : $sLink;
$sSubMenu = $this->getAllSubMenus($iItemID);
$sImgTabStyle = $sPictureRep = '';
if ($isBold && $sPicture != '') {
$sPicturePath = getTemplateIcon($sPicture);
$sPictureRep = "<img src='{$sPicturePath}' style='vertical-align:middle;width:16px;height:16px;' />";
$sText = ' ';
$sImgTabStyle = 'style="width:38px;"';
}
$sMainSubs = ($sSubMenu=='') ? '' : " {$sSubMenu} </a>";
$this->sCode .= "
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
<div id='submenu'>
<ul>
<li>{$sMainSubs}</li>
</ul>
</div>
</li>
";
}
}
$objMenu = new SimpleMenu();
echo "<ul id='ddmenu'>";
echo $objMenu->getCode();
echo "</ul>";
?>
It's difficult to tell exactly where you want to do this in your code, but I figure you're looking for something like:
<?php
for ($i = 0; i < 15; i ++){
echo "<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>"
}
echo "<li><a href='more' target='_parent'>More...</a>"
?>

Categories