当我使用自定义分类法单身时,在 wp_list_categories 上添加 current_cat 类 [英] Add current_cat class on wp_list_categories when I'm on single with custom taxonomy
问题描述
我在所有网络上搜索该答案.我使用 wp_list_categories 制作带有自定义分类法的子菜单,效果很好,并在浏览这些类别时放入 current-cat.
I search all the web for that answer. I use wp_list_categories to make a submenu with custom taxonomy, It works well, and puts current-cat when I browse those categories.
问题是,当我使用此菜单浏览单个帖子时,突出显示不再起作用.
The thing is, when I browse single posts with this menu, the highlight no more works.
对于该站点的博客部分,我使用以下代码突出显示 wp_list_categories() 上的当前类别:
For the blog part of that site, I use the following code to highlight current category on wp_list_categories():
function sgr_show_current_cat_on_single($output) {
global $post;
if( is_single() ) {
$categories = wp_get_post_categories($post->ID);
foreach( $categories as $catid ) {
$cat = get_category($catid);
if(preg_match('#cat-item-' . $cat->cat_ID . '#', $output)) {
$output = str_replace('cat-item-'.$cat->cat_ID, 'cat-item-'.$cat->cat_ID . ' current-cat', $output);
}
}
}
return $output;
}
add_filter('wp_list_categories', 'sgr_show_current_cat_on_single');
但据我尝试,无法使其适用于按自定义分类法排序的单个帖子.:/> 我不知道如何自定义它.
But as far as I tried, can't make it work for single posts that are ordered by custom taxonomy. :/ > I don't know how to custom it.
有可能吗?
推荐答案
你需要使用 get_the_terms( $id, $taxonomy );
而不是 wp_get_post_categories();
用于获取自定义分类术语 ID.
You need to use get_the_terms( $id, $taxonomy );
instead of wp_get_post_categories();
for getting custom taxonomy term IDs.
您可以将分类名称硬编码到函数中,或从您传入 wp_list_categories( $args );
的 $args
中获取.
You can hardcode taxonomy name into the functon or get it from the $args
you passed into wp_list_categories( $args );
.
最终代码:
add_filter( 'wp_list_categories', 'sgr_show_current_cat_on_single', 10, 2 );
function sgr_show_current_cat_on_single( $output, $args ) {
if ( is_single() ) :
global $post;
$terms = get_the_terms( $post->ID, $args['taxonomy'] );
foreach( $terms as $term ) {
if ( preg_match( '#cat-item-' . $term ->term_id . '#', $output ) ) {
$output = str_replace('cat-item-'.$term ->term_id, 'cat-item-'.$term ->term_id . ' current-cat', $output);
}
}
endif;
return $output;
}
这篇关于当我使用自定义分类法单身时,在 wp_list_categories 上添加 current_cat 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!