我的wordpress网站上有一个名为"schools"的自定义帖子类型。当您将鼠标悬停在学校选项卡上时,子菜单中会显示学校列表。这些是我用不同的学校名称创建的页面。现在,当您单击其中一个学校页面时,我有一个包含所有学校的侧边栏,以便他们可以从侧边栏浏览不同的学校,而不是使用菜单。
我使用以下代码片段填充了侧边栏。
while( $shools_loop->have_posts() ) : $schools_loop->the_post();
$content .= '<li class="schools-list">';
$content .= '<a href="'.get_permalink().'">'.get_the_title().'</a>';
$content .= '</li>';
endwhile;
这非常有效,我可以从侧边栏毫无问题地浏览所有学校。当我通过侧边栏或导航查看学校时,我正在尝试找到一种方法,当我在活动页面上时,我会为活动页面的 li 创建一些 css 样式。我已经想出了如何使用导航菜单执行此操作。但是需要侧边栏菜单上的帮助。由于正在填充侧边栏列表菜单,我不确定如何检查自定义帖子类型链接是否处于活动状态并与/schools/get-title 页面相对应。
我在网上找到了这样的东西,我试过编辑它,但我不确定这是否仅适用于导航菜单
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'services',
array(
'labels' => array(
'name' => __( 'Services' ),
'singular_name' => __( 'Services' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'services'),
)
);
}
// highlight active custom post page in nav
add_filter( 'nav_menu_css_class', 'namespace_menu_classes', 10, 2 );
function namespace_menu_classes( $classes , $item ){
if ( get_post_type() == 'services' ) {
// remove unwanted classes if found
$classes = str_replace( 'current_page_parent', '', $classes );
// find the url you want and add the class you want
if ( $item->url == 'services/physical-therapy-services/' ) {
$classes = str_replace( 'menu-item', 'menu-item current_page_parent', $classes );
}
}
return $classes;
}
基本上需要找到一种方法来检查自定义帖子类型是否处于活动状态。
您可以在主模板页面中设置一个global
变量,其中包含当前帖子的 ID,然后在侧边栏循环中,您可以检索该global
变量并使用get_the_ID()
函数将其与当前帖子的 ID 进行比较,然后执行必要的操作。
例:
单CPT.php
// Inside the loop
global $post_id = get_the_ID();
侧边栏-CPT.php
$post_id = isset($_GLOBALS['post_id']) ? $_GLOBALS['post_id'] : 0;
while( $shools_loop->have_posts() ) : $schools_loop->the_post();
if($post_id == get_the_ID()){
// This is the active link
$content .= '<li class="schools-list selected">';
} else {
$content .= '<li class="schools-list">';
}
$content .= '<a href="'.get_permalink().'">'.get_the_title().'</a>';
$content .= '</li>';
endwhile;