我通常在插件中包含以下父变量、过滤器和方法来解释这种情况。我从来都不确定这是不是一种“正确”的方式,但感觉比用javascript应用要好。
class Plugin_Name {
private $parent = \'services\'; // ideally this is a setting in your plugin, not a hard-coded variable in case the page slug changes
function __construct() {
// Add classes to \'parent\'
add_filter( \'nav_menu_css_class\', array( &$this, \'nav_parent_class\' ), 10, 2 );
}
function nav_parent_class( $classes, $item ) {
if ( $this->nicename == get_post_type() && ! is_admin() ) {
global $wpdb;
// 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 ));
// get page info
// - we really just want the post_name so it cane be compared to the post type slug
$page = get_page_by_title( $item->title, OBJECT, \'page\' );
// check if slug matches post_name
if( $page->post_name == $this->parent ) {
$classes[] = \'current_page_parent\';
}
}
return $classes;
}
}
根据您的请求,非插件路由。我没有测试这是否有任何错误,只是根据上面的课程改编,但它至少应该让你走上正确的方向:
add_filter( \'nav_menu_css_class\', \'nav_parent_class\', 10, 2 );
function nav_parent_class( $classes, $item ) {
$cpt_name = \'service\';
$parent_slug = \'services\';
if ( $cpt_name == get_post_type() && ! is_admin() ) {
global $wpdb;
// 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 ));
// get page info
// - we really just want the post_name so it cane be compared to the post type slug
$page = get_page_by_title( $item->title, OBJECT, \'page\' );
// check if slug matches post_name
if( $page->post_name == $parent_slug ) {
$classes[] = \'current_page_parent\';
}
}
return $classes;
}