Automatically add a first and last class WordPress menu items

This function gives the first and last WordPress menu items a class of “first” and “last”.

Note:
You can always go and add your own classes directly to the menu items yourself by going to Appearance > Menus, make sure you have the css classes option turned on in screen options at the top of your page, and enter the class of your choice.

But this function does this automatically. This is good if the client is going to be adding to the navigation. Place in your theme’s functions file.

// Add a last and first menu class option
function ac_first_and_last_menu_class($items) {
	foreach($items as $k => $v){
		$parent[$v->menu_item_parent][] = $v;
	}
	foreach($parent as $k => $v){
		$v[0]->classes[] = 'first';
		$v[count($v)-1]->classes[] = 'last';
	}
	return $items;
}
add_filter('wp_nav_menu_objects', 'ac_first_and_last_menu_class');