Add class to active top level (grandparent) menu item

Styling the top-level item if it’s active or a child is active is possible with pure CSS. Use the child selector, >, from the top:

.sidebar-navigation > ul > .current-menu-item,
.sidebar-navigation > ul > .current-menu-ancestor {}

If you want to add a new class, you can use the nav_menu_css_class filter. One of its parameters is $depth, which you can use to affect only top-level items. To tell if it’s child is active you can just check for the existence of the current-menu-item or current-menu-ancestor classes:

function wpse_310629_nav_menu_css_class( $classes, $item, $args, $depth ) {
    if ( $depth === 0 ) {
        if ( 
            in_array( 'current-menu-item', $classes ) || 
            in_array( 'current-menu-ancestor', $classes ) 
        ) {
            $classes[] = 'active-grandparent';
        }
    }

    return $classes;
}
add_filter( 'nav_menu_css_class', 'wpse_310629_nav_menu_css_class', 10, 4 );

Leave a Comment