Hay & Kilner Website Refresh
Hay & Kilner, a Facelift to an Existing CMS Driven Website
2 Comments
Walk To The World Cup - Campaign for Be Air Aware
Walk to the World Cup, a bespoke WordPress plugin
0 Comments
Service Network
Service Network, CMS based events driven website
0 Comments
Numark Pharmacists
Numark Pharmacists, CMS based website and membership based extranet
0 Comments

Adding a CSS Class to the the Last LI Generated by wp_nav_menu()

One of the great new features introduced in the latest WordPress (3.0) update is the menu feature. Now I’m not going to go an about how great all of this is and how life will never be the same because that’s getting a little tired now, but I did find myself needing to style the last items in both menu’s I was using to remove a pipe character from the footer menu and a background image from the main Nav. So for anyone interested heres how to add a class name to the the last LI in an UL generated by wp_nav_menu().

/* Add last_item class to last li in wp_nav_menu lists*/
function add_last_item_class($strHTML) {
	$intPos = strripos($strHTML,'menu-item');
	printf("%s last_item %s",
		substr($strHTML,0,$intPos),
		substr($strHTML,$intPos,strlen($strHTML))
	);
}
add_filter('wp_nav_menu','add_last_item_class');

You can add this example anywhere in your functions.php file. It’s worth mentioning that this example relies on you using the default list item classes provided by wp_nav_menu, but you can easily update this by adding the li class you are using:

$intPos = strripos($strHTML,'my-li-class-name');

There are tonnes of ways to do this but this is clean and simple string manipulation, so the overheads are quite low compared with the PREG/EREG approach.

Post a Comment

Your email is never shared. Required fields are marked *