How to loop through a possible 3rd level with wp_get_nav_menu_items()

This is my code which I am playing with based on examples I have found:

function create_bootstrap_menu( $theme_location ) {
if ( ($theme_location) && ($locations = get_nav_menu_locations()) && isset($locations[$theme_location])) {

$menu = get_term( $locations[$theme_location], ‘nav_menu’ );

$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = ‘<ul class=”navbar-nav mr-auto”>’ .”n”;

foreach( $menu_items as $menu_item ) {

if( $menu_item->menu_item_parent == 0 ) {

$parent = $menu_item->ID;
$menu_array = array();
foreach( $menu_items as $submenu ) {
if( $submenu->menu_item_parent == $parent ) {
$bool = true;
$menu_array[] = ‘<a class=”dropdown-item” href=”‘.$submenu->url.'”>’ . $submenu->title . ‘</a>’.”n”;
}
}
if( $bool == true && count( $menu_array ) > 0 ) {

$menu_list .= ‘<li class=”nav-item dropdown”>’ .”n”;
$menu_list .= ‘<a class=”nav-link dropdown-toggle” href=”#” id=”navbarDropdown” role=”button” data-toggle=”dropdown” aria-haspopup=”true” aria-expanded=”false”>’ . $menu_item->title .”</a>n”;

$menu_list .= ‘<div class=”dropdown-menu” aria-labelledby=”navbarDropdown”>’ .”n”;
$menu_list .= implode( “n”, $menu_array );
$menu_list .= ‘</div>’ .”n”;

} else {

$menu_list .= ‘<li class=”nav-item”>’ .”n”;
$menu_list .= ‘<a class=”nav-link” href=”‘ . $menu_item->url . ‘”>’ . $menu_item->title . ‘</a>’ .”n”;
}

}
// end <li>
$menu_list .= ‘</li>’ .”n”;
}

$menu_list .= ‘</ul>’ .”n”;

} else {
$menu_list = ‘<!– no menu defined in location “‘.$theme_location.'” –>’;
}

echo $menu_list;

}

create_bootstrap_menu(‘bs-mega-menu’);

It outputs the the primary level links, and dropdown links if available. But I am not sure how to also include an additional foreach loop here to display my third level links. Can someone teach me how to process that with this given example?

Many thanks for the lesson!

Read more here:: How to loop through a possible 3rd level with wp_get_nav_menu_items()

Leave a Reply

Your email address will not be published. Required fields are marked *