Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
    
Thank you, that is indeed what I was looking for . But at the end iI decided to use the screen options > css classes. But it can come in handy in the future. The reason I wanted this is because I recieved a html template with static classes –  Maartje Jan 20 at 11:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.