I’ve seen a lot of code on how to add a first
and last
class to a WordPress menu, but in my instance I would like to add a last
class to the last li in the sub-menu that WP generates. Here’s what I would like to achieve in it’s simplest form.
<ul>
<li>Menu item one</li>
<li class="has-sub-menu">Menu item two
<ul class="sub-menu">
<li>Sub menu item one</li>
<li>Sub menu item two</li>
<li class="last">Sub menu item three</li>
</ul>
</li>
<li>Menu item three</li>
</ul>
And here is what I currently have, that adds first and last classes to only the parent menu items. Could this be adapted?
function add_first_and_last($items) {
$items[1]->classes[] = 'first';
$items[count($items)]->classes[] = 'last';
return $items;
}
add_filter('wp_nav_menu_objects', 'add_first_and_last');
I would like to stick with php for this and not use either :last-child
(want it to work in ie7 & 8) or jQuery.
Put the following in your
functions.php
Usage
Where you use
wp_nav_menu
and you wish to have the ‘last’ class added, specify the walker above:theme_location
anddepth
can be whatever you like, the important part is thewalker
attribute.Side remarks
This code can be improved – potentially by un-setting each element in the
$children_elements[$parent_id]
array when its called and checking when it’s down to the last element (i.e. when it contains only one element). I thinkwp_list_filter
would be suitable here. This might not improve efficiency, but might be neater.Also, you can hard-code the parent and id fields – I’ve not done this for portability. The following class could be able to extend any of the provided extensions of the Walker Class (page lists, category lists etc).
The jQuery would look something like this;
But as for the PHP, please take a look at this answer provided by Rarst HERE and see if this helps you at all.
UPDATE
Rart’ solution from the above link does it fact work and the code snippet is;
The output gave me something like this;
Which then means you can style your
ul ul li
element via CSS selectors successfully.something to consider: while IE7 and IE8 don’t support last-child, they DO support first-child. so depending on what CSS you need to apply differently to the last item, you could reverse it.
also, FWIW, your theme is already using jQuery in other areas by default (comment section, for example) so that would be a quicker and cleaner option.