使用nav_menu_css_class()
滤器以下函数将当前菜单项类添加到由其slug标识的页面。你可以
更新$cpt_name
和$menu_item_id
反映设置的变量。
add_filter( \'nav_menu_css_class\', \'nav_parent_class\', 10, 2 );
function nav_parent_class( $classes, $item ) {
$cpt_name = \'team\';
$menu_item_id = 127; // id of menu item to add current-menu-item class to
if ( $cpt_name == get_post_type() && is_archive() && ! is_admin() ) {
// remove any active classes from nav (blog is usually gets the currept_page_parent class on cpt single pages/posts)
$classes = array_filter($classes, ($class == \'current_page_item\' || $class == \'current_page_parent\' || $class == \'current_page_ancestor\' || $class == \'current-menu-item\' ? false : true ));
// check if slug matches menu item id
if( $item->ID == $menu_item_id ) {
$classes[] = \'current-menu-item\';
}
}
return $classes;
}