WordPress: Add custom ID to final li in wp_nav_menu

I’m using three primary navs in my theme and I’m attempting to place a final link to the menu with a custom ID across all primary navs.

This is what I’m going for:

Read More
<nav id="menu" role="navigation" class="menu-primary">
  <ul id="nav" class="menu">
    <li id="menu-item-418" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-418"><a href="#">About</a></li>
    <li id="menu-item-474" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-474"><a href="#">Work</a></li>
    <li id="menu-item-463" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-463"><a href="#">Blog</a></li>
    <li id="menu-item-416" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-416"><a href="#">Contact</a></li>
    <li id="back" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-491"><href="#header">back</a></li>
  </ul>
</nav>

As you can see, the final li has an ID of ‘back’. Any idea how I can accomplish this without the use of js? I can see how I can change classes, but not ID’s. I’m doing this for CSS purposes.

Any help will be greatly appreciated!

Related posts

Leave a Reply

3 comments

  1. Instead of changing the id you can insert/inject another menu item/li at last as a custom menu item like following

    add_filter( 'wp_nav_menu_items', 'your_custom_menu_item');
    function your_custom_menu_item ($items)
    {
        $items .= '<li id="back" class="what-ever"><a href="#">Back</a></li>';
        return $items;
    }
    

    Just paste the code snippet in your functions.php and it will add a custom menu item in your menu. Hope this helps.

    Also there is another way to alter the menu using a custom walker and here is a nice example.

  2. If you are using wp_nav_menu, then the best way would be to use the classes provided by WordPress. I don’t think there’s a way to add specific id’s to menu items.

    Unless you do this with jQuery…

  3. You’re going to need to use JS/jQuery to do this. WordPress menus are dynamically written and you can’t just get in the theme file and edit the li’s.

    If your menus are not on the same page then you can use an ID and the first example. You would need to change the #nav to the ID of the UL for each menu and reiterate that one line 3 times, once for each menu.

    $(document).ready(function() {
       $('#nav li').last().attr('id', 'back');
    });
    

    If your menus are on the same page you’ll need to use a class like below. You would need to change the #nav to the ID of the UL for each menu and reiterate that one line 3 times, once for each menu. That is unless all the menus have a class on the UL, in which case you could just use $('#classNameHere li').last().addClass('back');.

    $(document).ready(function() {
       $('#nav li').last().addClass('back');
    });