0

I created some custom post types and custom taxonomies, if I'm on an archive page of the custom taxonomy, the Blog menu item is highlighted due to the current_page_parent class. Well this is obviously false and I want to remove the class, but I also want to add it to another menu item.

How can I add and remove the current_page_parent class dynamically for all my custom taxonomies?

I'm currently removing the class with

function wpdev_nav_classes( $classes ) {
  if( is_archive() ){
    $classes = array_diff( $classes, array( 'current_page_parent' ) );
  }
  return $classes;
}
add_filter( 'nav_menu_css_class', 'wpdev_nav_classes', 10, 2 );

but I have no clue on how to add it to an other menu item, let's call the item Example.

  • The 2nd argument passed to the nav_menu_css_class filter is the menu item, you can check the title, ID, etc.. – Milo Aug 22 '16 at 15:24
0

Replace news with your custom post type and menu-item-000 with the menu item you want to highlight.

function wpdev_nav_classes($classes) {
    // Remove "current_page_parent" class
    $classes = array_diff( $classes, array( 'current_page_parent' ) );

    // If this is the "news" custom post type, highlight the correct menu item
    if ( in_array('menu-item-000', $classes) && get_post_type() === 'news' ) {
        $classes[] = 'current_page_parent';
    }

    return $classes;
}
add_filter('nav_menu_css_class', 'wpdev_nav_classes');

If you have more than one post type, it would be better to use a switch statement. Let me know if that's the case, and I'll update the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.