Last Updated: February 25, 2016
·
840
· rihards

First & last CSS classes for WordPress nav menus

Sometimes you may want to have CSS classes that identify the first and last items in a menu, especially in those cases where you want to support browsers that don't support :first-child and :last-child selectors.

So here's a simple WordPress filter that you throw in your theme's functions.php file.

add_filter('wp_nav_menu_objects', 'first_and_last_menu_class', 10, 1);
function first_and_last_menu_class($items) {
    $items[1]->classes[] = 'menu-item-first';
    $item_count = count($items);
    for($i = $item_count; $i >=0; $i--) { 
        if($items[$i]->menu_item_parent == 0) {
            // found it
            $items[$i]->classes[] = 'menu-item-last';
            break;
        }
    }
    return $items;
}

Adding menu-item-first class is quite straightforward, we just add it to the first navigation item.

Last navigation item is a little more tricky. Because you have to make sure it's the last one with menuitemparent equal to 0, otherwise you end up assigning menu-item-last to a child menu item.