WordPress – Adding .active class to active menu item’s sub pages?

There is a problem in wp_nav_menu below:

Nav.php:

Read More
    $arg = array(
        'container' => false,
        'menu_class' => 'nav navbar-nav navbar-right'
    );
    wp_nav_menu($arg);

functions.php:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
    if( in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

Output:

<ul id="menu-quinn-menu" class="nav navbar-nav navbar-right">
<li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-15"><a href="http://xxx/">Home</a></li>
<li id="menu-item-14" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-6 current_page_item current_page_parent menu-item-14 active "><a href="http://xxx/work/">Work</a></li>
<li id="menu-item-13" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-13"><a href="http://xxx/shop/">Shop</a></li>
<li id="menu-item-12" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12"><a href="http://xxx/contact/">Contact</a></li>
</ul>

You can see the class active in the Work’s li, but when I go to the sub pages of Work (parent), the output:

<ul id="menu-quinn-menu" class="nav navbar-nav navbar-right">
<li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-15"><a href="http://xxx/">Home</a></li>
<li id="menu-item-14" class="menu-item menu-item-type-post_type menu-item-object-page current_page_parent menu-item-14"><a href="http://xxx/work/">Work</a></li>
<li id="menu-item-13" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-13"><a href="http://xxx/shop/">Shop</a></li>
<li id="menu-item-12" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12"><a href="http://xxx/contact/">Contact</a></li>
</ul>

You don’t see the class active in the Work’s li anymore.

Any ideas how I can have active in the Work’s li‘s sub pages?

Related posts

1 comment

  1. Try changing the block you pasted from your functions.php file from:

    add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
    function special_nav_class($classes, $item){
        if( in_array('current-menu-item', $classes) ){
            $classes[] = 'active ';
        }
        return $classes;
    }
    

    to:

    add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
    function special_nav_class($classes, $item){
        if( in_array('current_page_parent', $classes) ){
            $classes[] = 'active ';
        }
    return $classes;
    }
    

    Alternatively, you could also use CSS and select current_page_parent since WordPress automatically adds that class to the page’s parent as well.

Comments are closed.