Add current menu class to post type archive button when in single?

General Discussion 3 posts 2 voices

  1. This seems odd that it doesn’t already exist…

    You add a custom post type archive button into your main navigation, it adds a current-menu-item to the navigation as it should.

    You then click on a link into the single-custom-post.php page, but no class is added to the above custom post type archive link, its essentially its parent button but nothing is added.

    Is there anyway to add a parent class or something, so the main CPT archive button is highlighted when your on its children single page.

  2. This bit of code should do it. Just add to your theme’s functions.php file:

    add_filter( 'nav_menu_css_class', 'th_nav_menu_css_class', 10, 2 );
    
    function th_nav_menu_css_class( $classes, $item ) {
    
    	if ( 'post_type' === $item->type && is_singular( $item->object ) )
    		$classes[] = 'your-custom-class';
    
    	return $classes;
    }

    Be sure to change your-custom-class to the class name that you prefer.

    This might be something worth adding to Hybrid Core. Need a good name for the class. menu-item-parent-archive or something like that?

  3. Cheers Justin, yeah menu-item-parent-archive seems a sensible name.