filters - Add active class to top-level menu items when viewing single for that post type

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-

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 badges
Add a comment  | 

2 Answers 2

Reset to default 0

Take 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 );

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745527245a4631528.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信