Add class to all list items of wp_nav_menu

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.

Leave a Comment