WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Themes» How to Add the First and Last Class to WordPress Navigation Menu Items

How to Add the First and Last Class to WordPress Navigation Menu Items

Last updated on July 27th, 2012 by Editorial Staff
20 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Add the First and Last Class to WordPress Navigation Menu Items

Recently while working on a custom design project, we found a need to add some custom styling to our WordPress navigation menu items. This design in particular required different styling for the first menu item and the last menu item. Now we could easily go in the WordPress admin and add a custom css class to the first and last menu item. But because we are delivering this to a client, it is very likely that they might rearrange the order of menus in the future. Using the admin panel way of adding classes was not the most efficient method. So we decided to do it by using filters. In this article, we will show you how to style your first and last WordPress menu items differently by adding a .first and .last CSS class.

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

function wpb_first_and_last_menu_class($items) {
    $items[1]->classes[] = 'first';
    $items[count($items)]->classes[] = 'last';
    return $items;
}
add_filter('wp_nav_menu_objects', 'wpb_first_and_last_menu_class');

Another way to style the first and last menu items differently would be to use CSS selectors which works in most modern browsers.

ul#yourmenuid > li:first-child { }
ul#yourmenuid > li:last-child { }

Note: if you have a lot of users on older browsers (Internet Explorer), then you probably want to avoid the following technique.

We hope that this article has helped you. We have created a cheat sheet on default WordPress generated CSS classes which may come in handy when styling menu items as well.

20 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • How to Properly Move Your Blog from WordPress.com to WordPress.org

  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

19 Comments

Leave a Reply
  1. Ahmed Mahdi says:
    Oct 25, 2014 at 7:31 am

    i’ve changed the code slightly to work with child menus too:

    function wpb_first_and_last_menu_class($items) {

    foreach($items as $k => $v){
    $parent[$v->menu_item_parent][] = $v;
    }

    foreach($parent as $k => $v){
    $v[0]->classes[] = ‘first’;
    $v[count($v)-1]->classes[] = ‘last’;
    }

    return $items;

    }

    add_filter(‘wp_nav_menu_objects’, ‘wpb_first_and_last_menu_class’);

    Reply
  2. Trevor Simonton says:
    Jun 11, 2014 at 6:24 pm

    exactly what i needed. thank you!

    Reply
  3. Georgios Panagiotakopoulos says:
    Mar 30, 2014 at 5:36 am

    Thanks! This works great!

    Reply
  4. Munkhbayar says:
    Dec 17, 2013 at 1:44 am

    Thanks for code. Works for me.

    Reply
  5. mad_doc says:
    Nov 29, 2013 at 4:35 pm

    Thank you for idea & help!

    Reply
  6. Charles says:
    Nov 13, 2013 at 11:47 am

    Thanks for this nice code…

    What about child menu first and last item?
    It applied only for parent manu.

    Do you have any idea about child last item?

    Reply
  7. jordi says:
    Mar 30, 2013 at 1:29 pm

    Anyone have any tip about use add_filter(”); for wp_nav_menu using STARKERS?
    can’t make it works :( JS and CSS are fine to do that, it is just frustrating to don’t be able to fix it from the back…
    thanks to share anyway!!

    Reply
  8. Jake says:
    Oct 15, 2012 at 11:29 am

    This does not work reliably if you have nested menus.

    Reply
    • Editorial Staff says:
      Oct 15, 2012 at 11:32 am

      Hmm, will look into a fix for this.

      Reply
      • Olivier says:
        Oct 15, 2012 at 5:46 pm

        It works when the menu item is the last, or the last child of a last menu item.
        It does not work when the menu item is a last child of a menu item that is not the last.

        Reply
  9. Olivier says:
    Oct 9, 2012 at 11:40 am

    Together with some other additions to functions.php that i’ve tried, this code fails to tag a menu item as first or last menu item when they are in a submenu. A fix for this would be great!

    Reply
  10. Elliott Richmond says:
    Aug 5, 2012 at 6:48 am

    Nice! Would usually use CSS but this is a good tip

    Reply
  11. Mattia says:
    Jul 28, 2012 at 10:45 am

    Great! This is particularly interesting because I have to class more than 2 menu items…
    Now I got it!

    Thanks

    Reply
  12. karen says:
    Jul 28, 2012 at 10:01 am

    Thanks for this! Forgive me if I missed it – but – is there an example of the menu to see the difference in the nav created by this class? Thank you again!

    Reply
    • Editorial Staff says:
      Jul 28, 2012 at 2:19 pm

      The site we designed for our client is not live yet. But the main reason was that we wanted to have a border left to the first menu item. All other items had border right element with a specific padding and margin. We used the last class to remove the margin right and the border right because there was no need for it. It was hitting the wrap container. Hope you can visualize it.

      Reply
  13. Ivo Minchev says:
    Jul 28, 2012 at 9:30 am

    I’ve tried this at the site http://aurorachalet-switzerland.com/ and I cannot see the effect. I’m using the “Twenty Eleven” theme for this site. Where is the problem?

    Reply
    • Ivo Minchev says:
      Jul 28, 2012 at 9:32 am

      Pobably because of the #yourmenuid tag. I tried some ID’s but none of them worked.

      Reply
      • Editorial Staff says:
        Jul 28, 2012 at 2:22 pm

        This should work as long as you specify the correct id tags.

        Reply
    • Editorial Staff says:
      Jul 28, 2012 at 2:22 pm

      Don’t think that you are using the wp_nav_menu. From the looks of it, it seems that your site is using the fall_back menu by listing all pages. Can you confirm that you have gone into Appearance > Menu and created a menu there. Then specified that menu as a primary location??

      Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
WPForms Logo
WPForms
Drag & Drop WordPress Form Builder Plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2020 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2020)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2020)
    • SiteGround Reviews from 4196 Users & Our Experts (2020)
    • Bluehost Review from Real Users + Performance Stats (2020)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2020 – Step by Step Guide
Deals & Coupons (view all)
AWeber logo
AWeber Coupon
Get a completely FREE plan with AWeber, or 14.9% off the Pro plan. Start your email list today.
MonsterInsights Coupon Code
MonsterInsights Coupon
Get 50% off MonsterInsights, the best Google Analytics plugin for WordPress.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).
Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress CDN by MaxCDN | WordPress Security by Sucuri.