Add class to active element and its parent in nav menu

I am using the following code in order to add a class name “active” to the current menu item:

add_filter('nav_menu_css_class', 'add_active_class', 10, 2 );

function add_active_class($classes, $item) {
  if( $item->menu_item_parent == 0 && in_array('current-menu-item', $classes) ) {
    $classes[] = "active";
  }

  return $classes;
}

This works as charm, but only for items without a dropdown. If there’s an item with children in it, it won’t add the active class to the parent item.

Read More

Is there a way I can modify this code so the filter adds an “active” class both to the current link and it’s parent?

Related posts

1 comment

  1. Depending on the context you need this and working off of the code you have, you can try this:

    add_filter('nav_menu_css_class', 'add_active_class', 10, 2 );
    
    function add_active_class($classes, $item) {
      $class_names = array( 'current-menu-item', 'current-menu-ancestor', 'current-menu-parent', 'current_page_parent',  'current_page_ancestor' );
    
      if( $item->menu_item_parent == 0 && in_array( $class_names, $classes) ) {
        $classes[] = "active";
      }
    
      return $classes;
    }
    

    UPDATE: if above doesn’t work because of the array as needle for in_array function due to PHP version, try below code:

    add_filter('nav_menu_css_class', 'add_active_class', 10, 2 );
    
    function add_active_class($classes, $item) {
    
      if( $item->menu_item_parent == 0 && 
        in_array( 'current-menu-item', $classes ) ||
        in_array( 'current-menu-ancestor', $classes ) ||
        in_array( 'current-menu-parent', $classes ) ||
        in_array( 'current_page_parent', $classes ) ||
        in_array( 'current_page_ancestor', $classes )
        ) {
    
        $classes[] = "active";
      }
    
      return $classes;
    }
    

    If you want any current item to have the class active, you can do this:

    add_filter('nav_menu_css_class', 'add_active_class', 10, 2 );
    
    function add_active_class($classes, $item) {
    
      if( in_array( 'current-menu-item', $classes ) ||
        in_array( 'current-menu-ancestor', $classes ) ||
        in_array( 'current-menu-parent', $classes ) ||
        in_array( 'current_page_parent', $classes ) ||
        in_array( 'current_page_ancestor', $classes )
        ) {
    
        $classes[] = "active";
      }
    
      return $classes;
    }
    

Comments are closed.