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:

<?php

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