Hex1189
Hex1189

Reputation: 29

Wordpress - How to add active class to current menu item on only one specific menu?

So the following code works to get the current parent menu item active (highlighted with a different color background):

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
  if (in_array('current-menu-parent', $classes) || in_array('current- 
  menu-item', $classes)){
    $classes[] = 'active';
  }
     return $classes;
}

My only problem is that it also highlights the footer menu items. I want it to only affect the primary menu. I've made the following attempts to try to get it to work (in addition to some variations):

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 3);

function special_nav_class ($classes, $item, $args) {
  if ($args->theme_location == 'primary' && in_array('current-menu- 
  parent', $classes) || in_array('current-menu- 
  item', $classes)){
    $classes[] = 'active';
  }
     return $classes;
}

and

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 3);

function special_nav_class ($classes, $item, $args) {
  if ($args->theme_location == 'primary') {
    if (in_array('current-menu-parent', $classes) || in_array('current- 
    menu-item', $classes)){
    $classes[] = 'active';
    }
  }
     return $classes;
}

But it doesn't seem to work. The footer items are still affected.

Any thoughts?

Upvotes: 1

Views: 3603

Answers (2)

BlueDogRanch
BlueDogRanch

Reputation: 575

Try using the outer, enclosing CSS selector in the footer, i.e. #footer, to target the menu and menu items.

#footer #menu .current-menu-parent {background-color:#000 !important;}

Use dev tools in Firefox or Chrome or Safari or IE to check the exact selector.

Upvotes: 1

UpLinK
UpLinK

Reputation: 89

Weird.. 3rd example is working for me. Check wp_nav_menu() function calls, and menu areas in WP admin

wp_nav_menu(array('theme_location' => 'primary'));//header
wp_nav_menu(array('theme_location' => 'secondary'));//footer

And check WP version. You need 3.1+

Upvotes: 0

Related Questions