1

For a menu which has only top-level links to custom post type archive pages, how can I add the .active class to the top-level item when viewing that post type's single?

There's lots of similar questions on WPSE (like this or this), but none seem to address my specific question and make use of .current-menu-item or .current-menu-ancestor (and associated) classes, which don't appear on my menu (as I assume because the single posts aren't part of the menu list structure).

The only way I can think to do this is check the current post type against the slug, but it feels a bit hacky (and doesn't allow for url rewrites, etc).

0

Take a look at this link, which will help you add the class for custom post types: https://gist.github.com/gerbenvandijk/5253921

0

Solved using an adapted version of one of the answers from @mrbenhenson's link.

function custom_active_item_classes($classes = array(), $menu_item = false){            
global $post;
if ($menu_item->type == "post_type_archive" ) {
    $classes[] = ($menu_item->url == get_post_type_archive_link($post->post_type)) ? 'current-menu-item active' : '';
}
return $classes;
}

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

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.