Skip to content

Instantly share code, notes, and snippets.

@bUxEE
Last active April 28, 2024 15:07
Show Gist options
  • Save bUxEE/ac646bb23098e2bf521289b922c185bf to your computer and use it in GitHub Desktop.
Save bUxEE/ac646bb23098e2bf521289b922c185bf to your computer and use it in GitHub Desktop.
Recursive menu/submenu list from wp_get_nav_menu_items. Change menu name and style to your needs. Supports unlimited number of submenus.
<?php
$menu_name = 'menu-name';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
//echo '<pre>'.print_r($menuitems).'</pre>';
function buildTree( array &$elements, $parentId = 0 )
{
$branch = array();
foreach ( $elements as &$element )
{
if ( $element->menu_item_parent == $parentId )
{
$children = buildTree( $elements, $element->ID );
if ( $children )
$element->child = $children;
$element->has_children = 1;
$branch[$element->ID] = $element;
unset( $element );
}
}
return $branch;
}
$menuitems = buildTree($menuitems);
function create_menu($item) {
$link = $item->url;
$title = $item->title;
$id = $item->ID;
if(property_exists($item, 'child')) {
$children = $item->child;
?>
<li class="menu-item menu-item-<?php echo $id; ?> menu-has-children">
<div>
<?php echo $title; ?>&nbsp;<i class="fa fa-angle-double-down" aria-hidden="true"></i>
</div>
<ul class="dropdown-menu">
<?php
foreach($children as $child){
create_menu($child);
}
?>
</ul>
</li>
<?php
} else {
?>
<li class="menu-item menu-item-<?php echo $id; ?>">
<a href="<?php echo $link; ?>">
<?php echo $title; ?>
</a>
</li>
<?php
}
}
?>
<ul class="nav-ul">
<?php
foreach( $menuitems as $item ){
create_menu($item);
}
?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment