I’m using a WordPress Menu to create a navigation structured like this:
- Home
- About
- Contact
- Sub Page
Using this code from kuroi’s response here I’m able to add first-menu-item
and last-menu-item
classes to the list items above:
function add_first_and_last($output) {
$output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1);
$output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
return $output;
}
add_filter('wp_nav_menu', 'add_first_and_last');
However the last-menu-item
class is being added to the Sub Page list item (because it’s the last) rather than to the Contact list item.
Question: How can I make this function apply only to the top level items of a menu?
Thanks!
I would lean very much towards a custom walker for this but I think I’ve managed to make it work using part of that code and some of my own.
What I did was add
first-menu-item
andmiddle-menu-item
to top level items only with the first filter onnav_menu_css_class
. Then with the second filter I replaced the last occurrence ofmiddle-menu-item
withlast-menu-item
.It works for the few test cases I tried.
I have little fix on Bainternet code, because this code not work if last item has sub item
something like this:
I would recommend:
1) skip adding the first menu item class. That’s extra php that you don’t need. Using
ul > li:first-child
will let you target the first menu item in either CSS or as a jQuery selector.:first-child
has great browser support (more than :last-child, so I would add a class for the last menu item).2) Find the last top-level menu item and add a class to it. Drop this code into your theme’s functions.php file and it will add a class to only the last top-level navigation item instead of the very last navigation item like many of the code snippets in the other answers here.
Very late to the party, but was looking for something that handled doing this for submenus and subsubmenus also, ended up coming up with this, writing it out long-hand to with comments to help get my head around it.
Basically rather than trying to loop backwards, it loops forwards and checks the next menu item parent.
Good inclusion to my theme, hope it helps someone looking.