WordPress Add Leveling Classes to Menu Items

Many times when I am building mega menus and need additional classes to write cleaner CSS I like to add level classes to the WordPress menu items. I like to use a simple PHP function to add classes like .level-0, .level-1, .level-2 to the li depending on its depth from the top most nav item. Not only is my code cleaner, I also don't have to worry about item-id's or using nth-child() on anything.

Add to functions.php:

add_filter('wp_nav_menu_objects' , 'level_menu_classes');
function level_menu_classes($menu) {
    $level = 0;
    $stack = array('0');
    foreach($menu as $key => $item) {
        while($item->menu_item_parent != array_pop($stack)) {
        $stack[] = $item->menu_item_parent;
        $stack[] = $item->ID;
        $menu[$key]->classes[] = 'level-'. ($level - 1);
    return $menu;        
} ?>
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram