Skip to content

Instantly share code, notes, and snippets.

@kosinix
Last active October 14, 2016 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosinix/5459205 to your computer and use it in GitHub Desktop.
Save kosinix/5459205 to your computer and use it in GitHub Desktop.
Add first and last CSS class only to TOP LEVEL navigation menu items by using filters. CSS class will be added automatically without the need for tinkering with WordPress admin.
<?php
//Add extra css classes to menu items
function mytheme_nav_menu_css_class( $classes = array(), $item, $args ) {
$location_name = 'header';
static $top_level_count = 0; //Top level menu items counter
if($args->theme_location== $location_name){//Limit to this menu location only
if($item->menu_item_parent==0 and $top_level_count!==null){ //Count top level menu items
$top_level_count++; //Increment
}
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($top_level_count==count_top_level_menu_items($main_nav->term_id)){
$classes[] = 'last'; //Last top level menu item
$top_level_count = null; //Disable our counter, no need for it
}
}
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'mytheme_nav_menu_css_class', 10, 3 );
//Function to count the total number of top level menus. Useful for menus with sub menus
function count_top_level_menu_items($menu_id){
$count = 0;
$menu_items = wp_get_nav_menu_items($menu_id);
foreach($menu_items as $menu_item){
if($menu_item->menu_item_parent==0){
$count++;
}
}
return $count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment