WordPress nav_menu_css_class theme filter is not being called

I’m having problems getting a filter to work. I’m trying to add a class to each <li> element of a menu. This is on my theme’s functions.php file:

/**
 * Adds custom classes to the items in the nav menu
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function nav_menu_item_classes( $classes, $item, $args, $depth ) {

    // This is what I used to check that it's not working
    error_log("is nav_menu_item_classes working?");

    if ( 'menu-1' === $args->theme_location ) {
        // Add the Bootstrap nav-item class
        $classes[] = 'nav-item';
    }

  return $classes;

}

add_filter( 'nav_menu_css_class', 'nav_menu_item_classes', 10, 4 );

This is how I call the menu on my header.php file:

<?php
    wp_nav_menu( array(
        'theme_location' => 'menu-1',
        'menu_id'        => 'primary-menu',
        'menu_class'     => 'navbar-nav',
    ) );
?>

Everything seems to match, yet the filter is not executed. What could be wrong?

1 Answer
1

The nav_menu_css_class filter is located in the start_el function of WP’s walker class. As you can see in the source, there is no conditional execution here, so once the walker is called, the filter must be applied.

This bring us to wp_nav_menu, which calls the walker (through some intermediate calls) on the line where it says: $items .= walk_nav_menu_tree( $sorted_menu_items, $args->depth, $args );. So, if anything prevents the filter to be called, it must happen before this line. Actually there are three possibilities:

  1. First you see a filter called wp_nav_menu_args. If this is used it could be adding a custom walker that does not call the filter.

  2. Secondly there is the pre_wp_nav_menu filter. If this is used, the rest of the function is short circuited and never reaches the walker.

  3. Finally, if there are no items in your menu and no fallback is defined the walker will also be skipped. If there is a fallback (possibly added with wp_nav_menu_args) this will produce the output in stead of the walker.

Leave a Comment