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.
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?
Depending on the context you need this and working off of the code you have, you can try this:
UPDATE: if above doesn’t work because of the array as needle for in_array function due to PHP version, try below code:
If you want any current item to have the class active, you can do this: