2
votes

I've used the below code to add the active class to menu items. The site is 99% Ecomm using Woocommerce and I'm using product categories as top level navigation items. The below code works with almost all items except when being active on a product sub-category.

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

function special_nav_class ($classes, $item) {
    if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

Essentially, I'd like the top level nav item to be marked with the active class even when a sub-category has been selected.

1

1 Answers

0
votes

I think the best apporach to this is using javascript or jquery, let's say your menu looks like this :

<nav>
    <ul>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a>
            <ul>
                <li><a href="">Sub category</a></li>
                <li><a href="">Sub category</a></li>
                <li class="active"><a href="">Sub category</a></li>
                <li><a href="">Sub category</a></li>
            </ul>
        </li>
        <li><a href="">Top level</a></li>
        <li><a href="">Top level</a></li>
    </ul>
</nav>

All we need to do is to check which one of the top-level menus has an li with class active in them, so our jquery code looks like this:

<script>
    jQuery(document).ready(function(){
        // Adding class "active" to all top-level menus that contain an li.active item
        $('nav > ul > li').each(function(){
            if( $(this).has('li.active').length ) {
                $(this).addClass('active');
            }
        });
    });
</script>

Here's a fiddle