[Updated] Add first and last classes to menu items

One thing WordPress doesn’t do is add first and last classes to menu items in the navigation. Add this code to your functions.php file and you’ll have classes added to the first and last items in your menus for styling, etc.

first-last-menuI got the idea from this post in the WordPress support forums, but it breaks if there’s only one menu item. Seems like a small issue, but this fixes even that.

// add first and last menu item classes to navigation
function add_first_and_last($output) {
$count = substr_count($output, '/li');
if($count > 1){
$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');

Happy landings!

View Comments

Leave a Reply