nav_menu_css_class is a WordPress PHP filter that allows you to modify the CSS classes applied to a menu item’s <li>
element.
Usage
add_filter( 'nav_menu_css_class', 'your_custom_function', 10, 4 ); function your_custom_function( $classes, $menu_item, $args, $depth ) { // your custom code here return $classes; }
Parameters
$classes
(string[]): Array of the CSS classes applied to the menu item’s<li>
element.$menu_item
(WP_Post): The current menu item object.$args
(stdClass): An object ofwp_nav_menu()
arguments.$depth
(int): Depth of menu item, used for padding.
More information
See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/nav_menu_css_class/
Examples
Add a custom CSS class to all menu items
This example adds the CSS class my-custom-class
to all menu items.
add_filter( 'nav_menu_css_class', 'add_custom_class_to_menu_items', 10, 4 ); function add_custom_class_to_menu_items( $classes, $menu_item, $args, $depth ) { $classes[] = 'my-custom-class'; return $classes; }
Add CSS class based on menu item depth
This example adds a different CSS class based on the depth of the menu item.
add_filter( 'nav_menu_css_class', 'add_depth_based_class_to_menu_items', 10, 4 ); function add_depth_based_class_to_menu_items( $classes, $menu_item, $args, $depth ) { $classes[] = 'depth-' . $depth; return $classes; }
Remove all CSS classes from menu items
This example removes all CSS classes from menu items.
add_filter( 'nav_menu_css_class', 'remove_classes_from_menu_items', 10, 4 ); function remove_classes_from_menu_items( $classes, $menu_item, $args, $depth ) { return []; }
Add a CSS class to menu items with a specific title
This example adds the highlight
class to menu items with the title “Special”.
add_filter( 'nav_menu_css_class', 'add_class_to_specific_menu_item', 10, 4 ); function add_class_to_specific_menu_item( $classes, $menu_item, $args, $depth ) { if ( $menu_item->title == 'Special' ) { $classes[] = 'highlight'; } return $classes; }
Add a CSS class to the first menu item
This example adds the first-item
class to the first menu item.
add_filter( 'nav_menu_css_class', 'add_class_to_first_menu_item', 10, 4 ); function add_class_to_first_menu_item( $classes, $menu_item, $args, $depth ) { static $first_item = true; if ( $first_item && $depth == 0 ) { $classes[] = 'first-item'; $first_item = false; } return $classes; }