Home » Hooks » nav_menu_css_class

The nav_menu_css_class is a WordPress hook that allows developers to modify the CSS classes of navigation menu items. This hook is fired when the navigation menu is being generated, and it provides a way to add, remove, or modify the CSS classes applied to each menu item.

By default, WordPress generates CSS classes for menu items based on various factors such as the page’s current state (active, current, etc.), the menu item’s hierarchy, and custom classes specified by the user. However, there may be cases where you want to customize the CSS classes for a specific menu item or all menu items.

This hook provides a convenient way to manipulate the CSS classes by passing an array of existing classes as a parameter to the hooked function. Developers can then modify this array by adding or removing classes according to their needs, and return the modified array.

Here’s an example usage code that demonstrates how to use the nav_menu_css_class hook:

function custom_nav_menu_css_class($classes, $item, $args, $depth) {
    // Add a custom class to all menu items
    $classes[] = 'custom-class';

    // Remove a default class if present
    $classes = array_diff($classes, array('default-class'));

    // Add a class based on menu item depth
    $classes[] = 'depth-' . $depth;

    return $classes;
add_filter('nav_menu_css_class', 'custom_nav_menu_css_class', 10, 4);

In this example, we’ve created a function custom_nav_menu_css_class which is hooked to nav_menu_css_class using add_filter. Inside the function, we perform three actions:

  1. We add a custom class 'custom-class' to all menu items by appending it to the $classes array.
  2. We remove the default class 'default-class' if it exists in the $classes array using array_diff.
  3. We add a custom class based on the depth of the menu item by appending 'depth-' . $depth to the $classes array.

Finally, we return the modified $classes array. With this code, you can customize the CSS classes of your navigation menu items based on your specific requirements.

Learn More on

WordPress snippets using the nav_menu_css_class hook

Register an account to save your snippets or go Pro to get more features.