I have a wp_nav_menu
to which I want to add a classes to the list items.
I know this can be done by choosing ‘css classes’ from the screen options menu, but then I have to give every single li
a class.
I have a 2 depth menu.
(for example)
- All the normal li’s I want to give the class lidepth1
- All the sub menu li’s I want to give the class lidept2
Is this possible in the wp_nav_menu
function?
I searched the codex but I only found “link before” and “link after” but I don’t think that is what I need.
There is a nav_menu_css_class
filter. It is trivial to add classes.
function add_classes_wpse_130358($classes, $item, $args) {
$classes[] = 'new-class';
return $classes;
}
add_filter('nav_menu_css_class','add_classes_wpse_130358',1,3);
But you will probably need to extend Walker_Nav_Menu
or use the walker_nav_menu_start_el
filter instead, since the nav_menu_css_class
filter mysteriously does not have access to the depth
variable. But walker_nav_menu_start_el
doesn’t let you set the classes where you need to, so assuming your PHP is new enough…
function depth_classes_wpse_130358($item_output, $item, $depth, $args) {
add_action(
'nav_menu_css_class',
function() use ($depth) {
$depth++;
$classes[] = "depth-{$depth}";
return $classes;
}
);
return $item_output;
}
add_filter('walker_nav_menu_start_el','depth_classes_wpse_130358',1,4);
You will get a depth-N
for every level greater than 0.
I don’t recall ever needing to do this. The existing markup has always been sufficient, but there you go.