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).
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).
Share Improve this question edited Jan 28, 2019 at 9:44 mistertaylor asked Jan 24, 2019 at 10:40 mistertaylormistertaylor 6411 gold badge6 silver badges20 bronze badges2 Answers
Reset to default 0Take a look at this link, which will help you add the class for custom post types: https://gist.github/gerbenvandijk/5253921
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 );