I am trying to emulate the following navigation using wp_nav_menu
( https://developer.wordpress.org/reference/functions/wp_nav_menu/ ) in WordPress.
My demo menu structure:
Menu
>child1
>child2
>>submenu1
>>>subchild1
>>>subchild2
<nav class="collapse">
<ul class="nav nav-pills" id="mainNav">
<li class="dropdown">
<a class="dropdown-item dropdown-toggle" href="#">Page1</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">child1</a></li>
<li><a class="dropdown-item" href="#">child2</a></li>
<li class="dropdown-submenu"><a class="dropdown-item" href="#">submenu1</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">subchild1</a></li>
<li><a class="dropdown-item" href="#">subchild2</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
I am using the below code and was able to apply all the classes to the menu except for the dropdown-toggle
and dropdown-submenu
classes. I need to apply the dropdown-toggle
class to the first <a
class if it's a parent and I need to apply dropdown-submenu
to the li's that are submenus with children
<?php
wp_nav_menu(
array(
'theme_location' => 'primary',
'container' => 'nav',
'container_class' => 'collapse',
'container_id' => '',
'menu_class' => 'nav nav-pills',
'fallback_cb' => '',
'menu_id' => 'mainNav',
'link_class' => 'dropdown-item',
'depth' => 4,
'walker' => new Understrap_WP_Bootstrap_Navwalker(),
)
);
?>
I tried using:
function add_menu_parent_class( $items ) {
$parents = array();
foreach ( $items as $item ) {
//Check if the item is a parent item
if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
$parents[] = $item->menu_item_parent;
}
}
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
//Add "menu-parent-item" class to parents
$item->classes[] = 'dropdown-submenu';
}
}
return $items;
}
//add_menu_parent_class to menu
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
...in my functions.php
but it applies the dropdown-submenu
class to all the parent li's as opposed to just the submenu ones.
I was hoping someone may have a a PHP or jQuery solutions for this.
My goal is to reverse engineer the wp_nav_menu
into a theme I have as opposed to styling the classes wp_nav_menu
generates by default. I'm just a WP enthusiast so trying to learn as I go.
Thanks