Skip to content

Instantly share code, notes, and snippets.

@kosinix
Last active December 11, 2019 12:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kosinix/5459157 to your computer and use it in GitHub Desktop.
Save kosinix/5459157 to your computer and use it in GitHub Desktop.
Add first and last CSS class to WordPress navigation menu items by using filters. CSS class will be added automatically without need for tinkering with WordPress admin. Note: Last class will be added to the last menu item. If the last menu item has sub menu, the last class will be added to the last item of that sub menu.
<?php
//Add extra css classes to menu items
function mytheme_nav_menu_css_class( $classes = array(), $item, $args ) {
$location_name = 'header';
if($args->theme_location== $location_name){//Limit to this menu location only
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $location_name ] ) ) {
$main_nav = wp_get_nav_menu_object( $locations[ $location_name ] );
if ($item->menu_order == 1) {
$classes[] = 'first'; //First menu item
}
if ($item->menu_order >= $main_nav->count) {
$classes[] = 'last'; //Overall last menu item
}
}
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'mytheme_nav_menu_css_class', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment