WordPress Tutorial: Custom Menu's First and Last Classes

Today's WordPress tutorial is a quick one for fixing an annoying issue with custom WordPress menu's in which there is no ability to add first and last classes to menu items.

Simply place the following code into your functions.php file and the classes menu-item-first and menu-item-last will be added to your custom WordPress menus.

//Add first and last item classes to menus
add_filter( 'wp_nav_menu_items', 'nav_menu_first_last' );
function nav_menu_first_last( $items ) {
$position = strrpos($items, 'class="menu-item', -1);
$items=substr_replace($items, 'menu-item-last ', $position+7, 0);
$position = strpos($items, 'class="menu-item');
$items=substr_replace($items, 'menu-item-first ', $position+7, 0);
return $items; }