Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<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!

like image 999
user1867002 Avatar asked Oct 27 '25 04:10

user1867002


2 Answers

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.

like image 158
The Alpha Avatar answered Oct 29 '25 19:10

The Alpha


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...

like image 38
Jorge Flores Garcia Avatar answered Oct 29 '25 18:10

Jorge Flores Garcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!