nav_menu_submenu_css_class filter lets you modify the CSS classes applied to a submenu <ul> element in a WordPress navigation menu.
Usage
add_filter('nav_menu_submenu_css_class', 'your_custom_function', 10, 3); function your_custom_function($classes, $args, $depth) { // Your custom code here return $classes; }
Parameters
$classes
(string[]): Array of CSS classes applied to the submenu<ul>
element.$args
(stdClass): Object ofwp_nav_menu()
arguments.$depth
(int): Depth of the menu item, used for padding.
Examples
Adding a custom CSS class to all submenus
add_filter('nav_menu_submenu_css_class', 'add_custom_submenu_css_class', 10, 3); function add_custom_submenu_css_class($classes, $args, $depth) { $classes[] = 'custom-submenu-class'; return $classes; }
This code snippet adds a new CSS class custom-submenu-class
to all submenu <ul>
elements.
Adding a depth-based CSS class to submenus
add_filter('nav_menu_submenu_css_class', 'add_depth_based_submenu_css_class', 10, 3); function add_depth_based_submenu_css_class($classes, $args, $depth) { $classes[] = 'submenu-depth-' . $depth; return $classes; }
This code snippet adds a CSS class submenu-depth-X
to submenu <ul>
elements, where X is the depth of the submenu.
Removing all CSS classes from submenus
add_filter('nav_menu_submenu_css_class', 'remove_all_submenu_css_classes', 10, 3); function remove_all_submenu_css_classes($classes, $args, $depth) { return []; }
This code snippet removes all CSS classes from submenu <ul>
elements.
Adding a CSS class to submenus based on the menu location
add_filter('nav_menu_submenu_css_class', 'add_location_based_submenu_css_class', 10, 3); function add_location_based_submenu_css_class($classes, $args, $depth) { if ($args->theme_location === 'primary') { $classes[] = 'primary-submenu-class'; } return $classes; }
This code snippet adds a CSS class primary-submenu-class
to submenu <ul>
elements if the menu location is ‘primary’.
Adding a custom CSS class to submenus based on the number of child menu items
add_filter('nav_menu_submenu_css_class', 'add_child_count_based_submenu_css_class', 10, 3); function add_child_count_based_submenu_css_class($classes, $args, $depth) { $child_count = count($args->menu->items); $classes[] = 'child-count-' . $child_count; return $classes; }
This code snippet adds a CSS class child-count-X
to submenu <ul>
elements, where X is the number of child menu items.