When designing a WordPress theme you may want to add some .first and .last css classes to your WordPress navigation menus for styling purposes. This tutorial will show you how to acheive that by placing some filter code into your themes WordPress functions.php file that will modify all your menu items through “wp_nav_menu_objects” by adding .first and .last CSS classes allowing you to style menu items easily.
Step 1: Adding The Menus Modification WordPress Filter
Firstly you will want to open your current themes functions.php file then copy the code block below and paste it into your functions.php file at the bottom, close and save your functions.php file.
//------------- [ Add First & Last CSS Classes To Menu Output ] --------------// function add_first_and_last($items) { $items[1]->classes[] = 'first-menu-item'; $items[count($items)]->classes[] = 'last-menu-item'; return $items; } add_filter('wp_nav_menu_objects', 'add_first_and_last');
The code above will now automatically add the CSS class .first-menu-item to your menus first navigation item and also add the CSS class .last-menu-item to your menus last navigation item.
You can now easily style and use those css properties in your WordPress themes stylesheet, this is a technique I tend to use in all my themes for easy styling just in case it’s required during develpment.
Leave a Reply