WordPress is a powerful content management systems and one of the reason of its popularity is the level of customization it provides to developers and end users.
If you are looking to customize your theme navigation and want more granular control over the menu items then you can use ” wp_nav_menu_objects” filter. This filter takes two arguments
- $sorted_menu_items: The menu items, sorted by each menu item’s menu order.
- $args: An object containing wp_nav_menu() arguments.
Let suppose you want to add a custom class with first and last menu items of your main navigation element, then you will be doing like this
add_filter( 'wp_nav_menu_objects', 'wp_filter_menu_class', 10, 2 ); /** * Filters the first and last nav menu objects in your menus * to add custom classes. */ function wp_filter_menu_class( $objects, $args ) { // check for the right menu to remove the menu item from // here we check for theme location of 'primary' // alternatively you can check for menu name ($args->menu == 'menu_name') if ($args->theme_location != 'primary') return $objects; // Add "first-menu-item" class to the first menu object $objects[1]->classes[] = 'first-menu-item'; // Add "last-menu-item" class to the last menu object $objects[count( $objects )]->classes[] = 'last-menu-item'; // Return the menu objects return $objects; }
After you add the above code into your theme functions.php you will see that the said classes have been added on the very first and very last element of your “primary” navigation.