Bootstrap sub-menu items

Posted on in category: PHP

While people usually prefer a menu walker for wordpress menus. I recently implemented this approach in one of the projects.

function get_bootstrapmenuitems($current_menu) {
$menu_name = $current_menu;
$menu = wp_get_nav_menu_object( $menu_name);
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '';
for ($x = 0; $x < count($menu_items ); $x++) {
$menu_item= $menu_items[$x];
$skitit = false;
if($menu_items[$x + 1])
{
$next_parent_id = $menu_items[$x + 1]->menu_item_parent;
$curr_id = $menu_item->ID;
if ($curr_id == $next_parent_id)
{
$isactive = '';
if (get_queried_object_id() == $menu_item->object_id )
{
$isactive = 'active';
} else{
$isactive = '';
}
$menu_list .= 	'
<div class="btn-group">
   <li class="nav-item dropdown">
      <a class="nav-link btn btn-outline btn-block btn-rounded text-lg text-white waves-effect waves-light '.$isactive.'" href="#" id="navbarDropdown" data-toggle="dropdown">'.$menu_item->title.'</a>
      <ul class="dropdown-menu dropdown-menu-left onmenubar" role="menu">
         <li class="nav-item '.$isactive.'">';
            $stillhaschildren = true;
            while($stillhaschildren == true) {
            $next_parent_id = $menu_items[$x + 1]->menu_item_parent;
            if ($curr_id == $next_parent_id)
            {
            $menu_list .= 	' 
            <a href="'.$menu_items[$x + 1]->url.'" class="nav-link text-muted">'.$menu_items[$x + 1]->title.'</a>';
            $x += 1;
            } else
            {
            $stillhaschildren = false;
            $x -= 1;
            }
            } 
            $menu_list .= 	'
         </li>
      </ul>
   </li>
</div>
';
$skitit = true;
} 
}
if (!$skitit && !$menu_item->menu_item_parent ) {
$isactive = '';
if (get_queried_object_id() == $menu_item->object_id )
{
$isactive = 'active';
} else{
$isactive = '';
}
$menu_list .= '
<li class="nav-item '.$isactive.'"><a style="min-width: 130px;" class="nav-link btn btn-outline btn-block btn-rounded text-lg text-white  '.$isactive.'" qobject-id="'.get_queried_object_id().'" object-id="'.$menu_item->object_id.'" href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>
';
}
}
echo  $menu_list;
}