Skip to content

Instantly share code, notes, and snippets.

@kongondo
Last active December 17, 2019 12:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kongondo/e620370ffde03a2eb80a87ff952a25f4 to your computer and use it in GitHub Desktop.
Example Menu Builder 'Show More' Recursive Menu
<?php
/**
* Builds a nested list (menu items) of a single menu.
*
* A recursive function to display nested list of menu items.
*
* @param integer $parent ID of menu item to start build.
* @param WireArray $menu WireArray Object of menu items to display.
* @param integer $first Helper variable to designate first menu item and <ul></ul>.
* @return string $out Built menu output.
*
*/
function buildMenuFromObjectShowMore($parent = 0, $menu, $first = 0) {
if(!is_object($menu)) return;
$out = '';
$hasChild = false;
foreach ($menu as $m) {
$newtab = $m->newtab ? " target='_blank'" : '';
// if this menu item is a parent; create the sub-items/child-menu-items
if ($m->parentID == $parent) {
// if this is the first child
if ($hasChild === false) {
$hasChild = true;// this is a parent
if ($first == 0){
$out .= "<ul class='main-menu'>\n";
$first = 1;
}
// sub-menu
else $out .= "\n<ul class='sub-menu'>\n";
}
$class = $m->isCurrent ? ' class="current"' : '';
// a menu item
$out .= "<li {$class}><a href='{$m->url}' {$newtab}>{$m->title}</a>";
// show more if applicable
if($m->showMoreText) {
// get the show more item (object)
// @note: this function can as well just return the url, but the object offers more versatility
$showMoreParent = getShowMoreLink($m->parentID, $menu);
// if parent found
if(!is_null($showMoreParent)) {
$out .= " <span><a href='{$showMoreParent->url}'>{$m->showMoreText}</a></span>";
}
}
// call function again to generate nested list for sub-menu items belonging to this menu item.
$out .= buildMenuFromObjectShowMore($m->id, $menu, $first);
$out .= "</li>\n";
}// end if parent
}// end foreach
// close the <ul></ul>
if ($hasChild === true) $out .= "</ul>\n";
return $out;
}
/**
* Helper function to return the parent of a given menu item.
*
*
* @param Menu $parent ID of the parent menu item required.
* @param WireArray $menuItems WireArray Object of menu items to fetch parent item from.
* @return Menu|null $parentItem Menu Object if found, else null.
*
*/
function getShowMoreLink($parentID, $menuItems){
$parentItem = $menuItems->get("id={$parentID}");
return $parentItem;
}
// testing
$mb = $modules->get('MarkupMenuBuilder');
$options = array('include_children'=>1, 'm_max_level'=>2,'maximum_children_per_parent'=>3,'show_more_text'=>'more items...');
$menuItemsAsObject = $mb->getMenuItems(1234, 2, $options);
$menuFromObject = buildMenuFromObjectShowMore(0, $menuItemsAsObject);
echo $menuFromObject;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment