How to Add the First and Last Class to WordPress Navigation Menu Items


Recently while working on a custom design project, we found a need to add some custom styling to our WordPress navigation menu items. This design in particular required different styling for the first menu item and the last menu item. Now we could easily go in the WordPress admin and add a custom css class to the first and last menu item. But because we are delivering this to a client, it is very likely that they might rearrange the order of menus in the future. Using the admin panel way of adding classes was not the most efficient method. So we decided to do it by using filters. In this article, we will show you how to style your first and last WordPress menu items differently by adding a .first and .last CSS class.

All you have to do is open your theme’s functions.php file. Then paste the following the code:

  function wpb_first_and_last_menu_class($items) {      $items[1]->classes[] = 'first';      $items[count($items)]->classes[] = 'last';      return $items;  }  add_filter('wp_nav_menu_objects', 'wpb_first_and_last_menu_class');  

Another way to style the first and last menu items differently would be to use CSS selectors which works in most modern browsers.

  ul#yourmenuid > li:first-child { }  ul#yourmenuid > li:last-child { }  

Note: if you have a lot of users on older browsers (Internet Explorer), then you probably want to avoid the following technique.

We hope that this article has helped you. We have created a cheat sheet on default WordPress generated CSS classes which may come in handy when styling menu items as well.

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.