Easily Add Custom Classes to Your First and Last Menu Items in WordPress

https://gist.github.com/thomasgriffin/4253190

Below is the code to do this programatically, it is worth noting that you can add classes via the menus page in the wp-admin by selecting Screen Options and then CSS Classes. The below code may be better for instances where you don’t want to depend on users to remember to add the classes manually.

add_filter( 'wp_nav_menu_objects', 'tgm_filter_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 tgm_filter_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;

}

Revisions

No comments yet.

Leave a Reply