While designing Concise theme, we wanted to be able to target the last item in the menu to allow us to style the menu as what we wanted it to be. However, there’s no default specific CSS class available to target the menu.
Although we can use pseudo :last-child
and :first-child
class, there might be a cross browser compatible issue for older browser and therefore might not be the best option.
Adding a class for the first and last menu item is quite easy actually. Thankfully, there’s wp_nav_menu_objects
filter available. Here’s a working code snippet that can be placed on your functions.php
file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Hat tip to Thomas Griffin for this awesome snippet. What the code does is basically add .first-menu-item
class to the first item in the menu and .last-menu-item
class to the last item in the menu.
As in the case of Concise theme, using .last-menu-item
class, we were able to target the last item in the menu to remove the separator as you can see from the image below:
We hope this tutorial helped you to add custom classes to the first and last menu item in WordPress. If you want more example on using wp_nav_menu_objects
filter, we recommend you check out WordPress Codex page.
suresh says
thanks for sharing this nice information about wordpress menu.because it neccesry thing for a wordpress blogger.helpful post