3

I'm using wp_nav_menu in Wordpress to create my navigation

The output is similar to this(I have removed href links)

    <nav id="pageNav">
        <ul id="menu-headernav" class="menu">
          <li><a href="">Home</a></li>
        <li><a href="">About</a></li>
        <li><a href="">Services</a></li>
        <li><a href="">Work</a></li>
        <li><a href="">Contact</a></li>
      </ul>         
    </nav>

I need to style each link separately.

How can I add an id to each (li) or (a) in the menu so I can style it.

2 Answers 2

7

For the a tag, you can add an id attribute by writing in function in your theme's function.php file and hook into the nav_menu_link_attributes filter.

Check out the WordPress core at: http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/nav-menu-template.php#L89

function my_id_attribute ($atts, $item, $args) {
  //develop your anchor tag ID nomenclature I'll call it $id
  $atts['id'] = $id;
  return $atts;
  }
add_filter('nav_menu_link_attributes', 'my_id_attribute', 10, 3);

For the li tag, you can use the nav_menu_item_id filter to modify the id attribute.

function my_li_id_handler ($id, $item, $args) {
 //the $item variable is a WP_Post instance...handy properties are $item->post_title, $item->post_name and $item->menu_order
 //do your id nomenclature work here.
 return $id;
}
add_filter('nav_menu_item_id','my_li_id_handler', 10, 3);
5

You can add a class for each menu item from within wordpress. Go to "Appearance" -->"Menus" --> and then in the screen options panel, click the checkbox to activate "CSS Classes". From there you can assign unique selectors to your menu items for your CSS to target.

2
  • This is the easiest way. Best not to use a hook unless you really need it. Oct 29, 2016 at 0:30
  • 4
    This is very useful to know about, but doesn't (currently) allow for setting the id attribute as was requested.
    – Sean
    Jan 17, 2017 at 2:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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