Sometimes you want to be able to style your first and/or last menu items differently from the rest. Maybe you want to remove padding, shift margins, or the like.
I’ve got an easy solution to add custom classes to both the first and last menu items in your menus so that you can style each appropriately. This is done with code on the server side, so the effects applied are instant, and you never have to worry about someone changing classes inside the menu admin area in WordPress.
**Note: I am assuming you are using WordPress 3.0 navigation menus in the tutorial.
The code snippet below will apply the classes to all menus on your site:
If you want to go a step further and limit this to only a particular navigation menu on your site, check out the code below:
This limits the classes being applied to the primary navigation menu only. You could extend this to include or exclude other registered navigation menus for your site.
Now if you have noticed above, these two pieces of code are really only effective for top level menus (e.g. menus with no dropdowns). If you want to add the same class structure to nested menus, use the code below. It will do the exact same thing as above, except for it will apply the logic to all nested submenus in your menu structure.
You can take the logic from the second bit of code and apply it to this as well if you only want this to work on particular menus.
Simply comment out classes that you don’t need (e.g. no custom class on the first menu item), and you should be all set! I use this on basically every project I do, so hopefully you will find it useful too!
I live and breathe WordPress. I create products around WordPress (Soliloquy and OptinMonster), contribute to WordPress core and do lots of fun development around WordPress in general. You can find me on Twitter, Facebook and Google+.
I have created over 100 custom themes and plugins for clients of all shapes and sizes. I have also contributed to WordPress Core, spoken at several WordCamps and created some powerful WordPress products.
I create solutions that add value to your business.