ThisCalculator

Everyday

Add First & Last Classes to WordPress Menu Items

Updated · Standard formula, shown below

This guide shows you how to automatically add first and last CSS classes to the first and last items in your WordPress navigation menus. This makes it easy to style the edges of your menu—like rounding the first corner or adding a divider after the last item—without manually editing each menu item. You’ll need a WordPress site with a theme that uses standard menu functions, plus access to your theme’s functions.php file or a code snippet plugin.

What You’ll Need

  • A WordPress site (self-hosted or managed) with at least one registered menu.
  • Access to your theme’s functions.php file via Appearance → Theme File Editor, or a code snippets plugin like Code Snippets.
  • Basic understanding of PHP and CSS (just enough to paste and tweak code).

Step-by-Step

  1. Back up your site. Before editing any theme file, create a full backup of your WordPress files and database. This ensures you can restore if something breaks.
  2. Open your theme’s functions.php. In your WordPress admin, go to Appearance → Theme File Editor. In the right-hand file list, click functions.php. Alternatively, use an FTP client or your hosting file manager to edit the file locally and upload it.
  3. Add the PHP filter function. Copy and paste the following code at the end of the file, before the closing ?> tag (or just at the end if there’s no closing tag):
    add_filter('nav_menu_css_class', 'add_first_last_menu_classes', 10, 2);
    function add_first_last_menu_classes($classes, $item) {
        global $wp_query;
        // Get the menu items for the current menu location
        $locations = get_nav_menu_locations();
        $menu = wp_get_nav_menu_object($locations['primary']); // Change 'primary' to your menu location
        if ($menu) {
            $menu_items = wp_get_nav_menu_items($menu->term_id);
            if ($menu_items) {
                // Find the first and last item IDs
                $first_item_id = $menu_items[0]->ID;
                $last_item_id = $menu_items[count($menu_items)-1]->ID;
                // Add classes
                if ($item->ID == $first_item_id) {
                    $classes[] = 'first';
                }
                if ($item->ID == $last_item_id) {
                    $classes[] = 'last';
                }
            }
        }
        return $classes;
    }

    Important: Change 'primary' to the actual location slug of your menu. You can find this in Appearance → Menus → Manage Locations (the theme location name, e.g., ‘primary’, ‘header-menu’, ‘main-menu’).

  4. Save the file. Click the “Update File” button. If you’re using a code snippets plugin, paste the same code into a new snippet and activate it.
  5. Test your menu. View your site’s front end and inspect the menu HTML using your browser’s developer tools (right-click on a menu item → Inspect). The first and last <li> elements should have the classes first and last respectively.
  6. Add CSS (optional). To style these classes, go to Appearance → Customize → Additional CSS and add rules like:
    .menu-item.first { border-radius: 5px 0 0 5px; }
    .menu-item.last { border-radius: 0 5px 5px 0; }

    Adjust the styles to your needs.

Common Mistakes

  • Wrong menu location slug. Using a location that doesn’t exist or isn’t assigned to a menu will cause the function to do nothing. Double-check the slug in your theme’s code (often in register_nav_menus()).
  • Multiple menus. The code above only works for one location. If you have multiple menu locations (e.g., header and footer), you need to adapt the function to loop through all locations or create separate hooks.
  • Sub-menu items. The classes are added only to top-level items because wp_get_nav_menu_items() returns all items, but the first and last in the flat list are the first and last top-level items (assuming no sub-menu items appear before the first top-level item—which they don’t in the default order). However, if you have a sub-menu that appears in the list, the last item might be a sub-item. The code above uses the flat list, so it’s generally fine, but be aware.
  • Not clearing cache. If you use a caching plugin, the changes may not appear immediately. Clear all caches after adding the code.

Tips

  • Use a child theme. If you edit functions.php in your parent theme, changes will be lost on theme updates. Use a child theme’s functions.php instead.
  • Use a code snippets plugin. This is safer than editing theme files directly, as it prevents syntax errors from breaking your site. Plugins like Code Snippets allow you to add PHP without touching the theme.
  • Test on a staging site. If possible, test the code on a staging copy of your site before applying it to production.
  • Make the function more robust. You can extend it to handle multiple locations by checking each location in a loop, or by using a different approach like comparing the item’s position in the rendered menu (which is more complex).

Troubleshooting

No classes appear. First, verify that the menu location slug is correct. You can temporarily add error_log(print_r($locations, true)); to see what locations are registered. Also, ensure that the menu is actually assigned to that location in Appearance → Menus.

Site shows a white screen (PHP error). This usually means a syntax error in your code. Check the exact code you pasted, especially the quotes and semicolons. If you can’t access the admin, use FTP to remove the code or restore the backup.

Classes appear but on wrong items. This can happen if your menu has sub-items and the flat list order is not what you expect. In that case, you might need to filter only top-level items by checking $item->menu_item_parent == 0 and then find the first and last among those. Here’s an improved version:

add_filter('nav_menu_css_class', 'add_first_last_menu_classes_top', 10, 2);
function add_first_last_menu_classes_top($classes, $item) {
    if ($item->menu_item_parent != 0) return $classes; // only top-level
    $locations = get_nav_menu_locations();
    $menu = wp_get_nav_menu_object($locations['primary']);
    if ($menu) {
        $menu_items = wp_get_nav_menu_items($menu->term_id);
        $top_items = array_filter($menu_items, function($mi) { return $mi->menu_item_parent == 0; });
        $top_items = array_values($top_items); // re-index
        if (count($top_items) > 0) {
            if ($item->ID == $top_items[0]->ID) $classes[] = 'first';
            if ($item->ID == $top_items[count($top_items)-1]->ID) $classes[] = 'last';
        }
    }
    return $classes;
}

Cache is the culprit. If you’ve cleared all caches and still don’t see changes, try a different browser or incognito mode to rule out browser caching.

Frequently Asked Questions

Can I add these classes to a specific menu only?

Yes, the code above already targets a specific menu location. If you want to target a menu by its name (e.g., ‘Main Menu’), you can use wp_get_nav_menu_object('Main Menu') instead of using the location.

Will this work with all themes?

Yes, as long as the theme uses standard WordPress menu functions like wp_nav_menu(). The filter hook nav_menu_css_class is core WordPress, so it works across all themes.

Do I need to know PHP to do this?

You only need to copy and paste the code and change one variable. No deep PHP knowledge is required. However, understanding basic PHP syntax helps if you need to customize it.

Can I add other classes like ‘first’ and ‘last’ to all menu items?

Yes, you can modify the function to add any class to any item based on its position. For example, you could add a class to every second item, but that requires more complex logic.

What if I have multiple menus in different locations?

You can either duplicate the function for each location (changing the location slug) or write a more generic function that loops through all registered locations. The latter is more efficient but requires more code.

Is there a plugin that does this?

Yes, plugins like “Menu Item Classes” or “CSS Menu Class” allow you to add custom classes to individual menu items via the menu editor. However, the code approach is lightweight and doesn’t require an extra plugin.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.