How to Add Custom Classes to First and Last Items in WordPress Menu

While designing Concise theme, we wanted to be able to target the last item in the menu to allow us to style the menu as what we wanted it to be. However, there’s no default specific CSS class available to target the menu.

Although we can use pseudo :last-child and :first-child class, there might be a cross browser compatible issue for older browser and therefore might not be the best option.

Adding a class for the first and last menu item is quite easy actually. Thankfully, there’s wp_nav_menu_objects filter available. Here’s a working code snippet that can be placed on your functions.php file.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
<?php
add_filter( 'wp_nav_menu_objects', 'afn_custom_menu_class' );
/**
* Filters the first and last nav menu objects in your menus
* to add custom classes.
*
* @since 1.0.0
*
* @param object $objects An array of nav menu objects
* @return object $objects Amended array of nav menu objects with new class
*/
function afn_custom_menu_class( $objects ) {
// Add "first-menu-item" class to the first menu object
$objects[1]->classes[] = 'first-menu-item';
// Add "last-menu-item" class to the last menu object
$objects[count( $objects )]->classes[] = 'last-menu-item';
// Return the menu objects
return $objects;
}
view raw functions.php hosted with ❤ by GitHub

Hat tip to Thomas Griffin for this awesome snippet. What the code does is basically add .first-menu-item class to the first item in the menu and .last-menu-item class to the last item in the menu.

As in the case of Concise theme, using .last-menu-item class, we were able to target the last item in the menu to remove the separator as you can see from the image below:

custom classes

We hope this tutorial helped you to add custom classes to the first and last menu item in WordPress. If you want more example on using wp_nav_menu_objects filter, we recommend you check out WordPress Codex page.

Comments

  1. suresh says

    thanks for sharing this nice information about wordpress menu.because it neccesry thing for a wordpress blogger.helpful post

Leave a Reply

Your email address will not be published. Required fields are marked *