Add levels selector class to wordpress nav menu

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:

Read More
<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!

Related posts

Leave a Reply

3 comments

  1. 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;        
    }