Skip to main content

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; }

 

Looking for Expert WordPress or Drupal development?

I am a freelance website developer and designer based in the UK. I work as a remote Drupal developer, WordPress developer and Front-end developer for a variety of startups, charities and international businesses in Bristol, Bath, London and Europe. You can learn more about me by visiting my resume page.

Get in touch for a free quote on your next project and if you want to connect me with then check out my LinkedIn profile.