Filtering active menu element class on WordPress

When using a navigation menu on WordPress, you’ve probably seen the various HTML classes that are added on active elements, such as current-menu-item, current-menu-parent, current-menu-ancestor

While that kind of classes are fine if you must fully reflect the navigation hierarchy on the menu element, there are some times that you just need a more simple approach, such as just knowing when a certain menu element must look like the active item —for instance, when using Bootstrap.

For these kind of situations, you can use a simple filter to add such a class; something like:

<br />
<p>add_filter('nav_menu_css_class', function ($classes, $item, $args, $depth) {<br />
    // filter by some condition... for instance, only on the &quot;main&quot; menu<br />
    if ( $args-&gt;theme_location !== 'main' ) {<br />
        return $classes;<br />
    }<br />
    // all the different &quot;active&quot; classes added by WordPress<br />
    $active = [<br />
        'current-menu-item',<br />
        'current-menu-parent',<br />
        'current-menu-ancestor',<br />
        'current_page_item'<br />
    ];<br />
    // if anything matches, add the &quot;active&quot; class<br />
    if ( array_intersect( $active, $classes ) ) {<br />
        $classes[] = 'active';<br />
    }<br />
    return $classes;<br />
}, 10, 4);<br />