I would like to add level classes to each li when echoing the results of wp_list_pages. Currently, I'm using:
<?php
wp_nav_menu(array('theme_location' => 'main_menu', 'container' => '', 'menu_class' => 'fR clearfix', 'menu_id' => 'nav'));
<?php } ?>
The desired output would be:
<ul class="menu">
<li class="page_item page-item-9 level-0 current_page_item"><a href="" title=""></a>
<ul class="children expanded" style="display: block; ">
<li class="page_item page-item-40 level-1"><a href="" title=""></a></li>
<li class="page_item page-item-43 level-1"><a href="" title=""></a></li>
<li class="page_item page-item-45 level-1"><a href="" title=""></a></li>
<li class="page_item page-item-47 level-1"><a href="" title=""></a></li>
</ul>
</li>
<!-- So on -->
</ul>
Is this possible to have the desired output? please help!
There isn't a direct way to do this.
You can use the wp_nav_menu_objects filter and manipulate the menu item's classes.
Here is the code for you:
<?php
add_filter('wp_nav_menu_objects' , 'my_menu_class');
function my_menu_class($menu) {
$level = 0;
$stack = array('0');
foreach($menu as $key => $item) {
while($item->menu_item_parent != array_pop($stack)) {
$level--;
}
$level++;
$stack[] = $item->menu_item_parent;
$stack[] = $item->ID;
$menu[$key]->classes[] = 'level-'. ($level - 1);
}
return $menu;
}
It's best to use a custom walker to add that class. See Cleaner output for wp_nav_menu() and Improve your Wordpress Navigation Menu Output and T5_Nav_Menu_Walker_Simple — Gist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With