Add First and Last Class to Navigation Menu Items

How to Add First and Last Class to Navigation Menu Items

in Functions
Google+ LinkedIn

In version 3.0 WordPress presented us with the new Menus functionality, it completely changed the way we use navigation menus in WordPress. Now we can easily manage our navigation menus and include pages, custom links and categories without hacking page listing functions or creating our own custom function. We can simply drag and drop menu items in WordPress admin panel to create a menu and wp_nav_menu function outputs it on front end website. By default menu items has number of classes so we can assign CSS styles as we want. But sometimes you want to be able to style your first and/or last menu items differently from the rest. Maybe you want to remove padding, shift margins, or the like.

Recently I faced a similar problem on a project, where I needed to remove margins of first and last item of navigation menu. Although I could easily do that by using menu item ID classes to apply CSS rules but it is not the most efficient method because navigation menu might break if we change or rearrange menu items in future. Instead I used a filter to add first and last classed to first and last WordPress menu items. This will make sure that we will never have to worry about someone changing/or rearranging menus in admin area.

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

// add first and last class to navigation menu items
function wcs_add_custom_menu_classes( $objects ) {

    // add "first-menu-item" class to the first menu item
    $objects[1]->classes[] = 'first-menu-item';

    // Add "last-menu-item" class to the last menu item
    $objects[count( $objects )]->classes[] = 'last-menu-item';

    // Return the menu objects
    return $objects;

add_filter( 'wp_nav_menu_objects', 'wcs_add_custom_menu_classes' );


Share the love

If you like this snippet, share it with others!

Leave a Reply

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