DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

How to Add First and Last Classes to WordPress Navigation Menu Items

Use the wp_nav_menu_objects filter to add first and last classes to top-level items in a classic WordPress menu, then style their links with CSS.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a classic PHP-rendered WordPress menu, use the wp_nav_menu_objects filter to identify the first and last top-level menu items and add CSS classes to their class arrays. WordPress carries those classes onto each item’s <li>, where your CSS can target the link. The example below adds menu-item-first and menu-item-last.

Add classes to the first and last top-level items

Place this code in a small site-specific plugin or your child theme’s functions.php. It treats “first” and “last” as the first and last top-level items, excluding submenu items.

As an Amazon Associate I earn from qualifying purchases.

function example_add_first_last_menu_item_classes( $items, $args ) {
    $top_level_items = array();

    foreach ( $items as $item ) {
        if ( 0 === (int) $item->menu_item_parent ) {
            $top_level_items[] = $item;
        }
    }

    $count = count( $top_level_items );

    if ( 0 === $count ) {
        return $items;
    }

    $top_level_items[0]->classes[] = 'menu-item-first';
    $top_level_items[ $count - 1 ]->classes[] = 'menu-item-last';

    return $items;
}
add_filter( 'wp_nav_menu_objects', 'example_add_first_last_menu_item_classes', 10, 2 );

wp_nav_menu_objects filters the sorted menu-item objects before WordPress generates the HTML. The core Walker_Nav_Menu then applies nav_menu_css_class to the classes for each item’s <li>. Updating the objects’ class arrays is therefore more direct than modifying the rendered HTML. See the wp_nav_menu() reference and Walker_Nav_Menu reference.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use CSS selectors that account for the classes being on the list items:

.menu-item-first > a {
    /* styles for the first top-level link */
}

.menu-item-last > a {
    /* styles for the last top-level link */
}

Menus displayed with wp_nav_menu() can be styled through their classes; inspect the generated markup if your theme changes the usual structure. The WordPress Theme Handbook’s navigation menu guide describes the classic menu output path.

Choose what “first” and “last” mean

Top-level menu only

The example checks whether menu_item_parent is zero, so it assigns the classes to the first and last top-level items only. This is usually what a horizontal site navigation needs.

First and last within each submenu

If each submenu also needs its own first and last classes, group items by their parent and determine positions separately within each group. A single first/last calculation across the whole item list does not identify the ends of every submenu.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A menu with one top-level item

With one qualifying item, the same item is both first and last, so the snippet adds both classes. If your styling requires only one class in that case, add an explicit condition for a count of one.

Limit the change to the intended menu

The snippet applies to the menu items passed through the filter. If the site renders multiple menus, scope the change to the desired menu or theme location using the filter’s $args, and leave other menus unchanged. WordPress’s wp_nav_menu() reference documents that a menu can be selected by menu or registered theme location.

Also check what happens when a requested menu or location is missing: WordPress can use a fallback callback to render a page menu. If the output looks unexpected, verify the menu assignment, the fallback behavior, and the actual generated HTML.

Rank #4
Teacher Record Book
  • Keep track of everything from attendance to test scores
  • Spiral bound
  • Measures 8-1/2" x 11"
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use the filter that matches the change

wp_nav_menu_objects is useful when the logic depends on relative position in the complete sorted item list. For a condition that can be decided one item at a time, nav_menu_css_class filters the classes for an individual <li>. By contrast, wp_nav_menu_items receives the rendered list HTML as a string, so it is less direct for assigning item classes. See the wp_nav_menu_items hook reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A custom walker is generally unnecessary for this class change; consider one only when you need broader changes to conditional menu markup. This code applies to classic PHP-rendered menus using wp_nav_menu(). For a block-based navigation implementation or a theme with a custom walker, inspect how that implementation renders classes before using the snippet unchanged.

Verify the result

  1. Save the code in a site-specific plugin or child theme, not WordPress core.
  2. Load the page that displays the intended menu and inspect its rendered HTML.
  3. Confirm that menu-item-first and menu-item-last appear on the expected <li> elements.
  4. Check that your CSS selector matches the theme’s actual markup and that other menus were not changed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.