0

我在整个网络上搜索该答案。我使用 wp_list_categories 制作一个带有自定义分类法的子菜单,它运行良好,并在我浏览这些类别时放置 current-cat。

问题是,当我使用此菜单浏览单个帖子时,突出显示不再起作用。

对于该站点的博客部分,我使用以下代码突出显示 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');

但据我尝试,无法使其适用于按自定义分类法排序的单个帖子。:/ >我不知道如何自定义它。

甚至可能吗?

4

1 回答 1

2

您需要使用get_the_terms( $id, $taxonomy );而不是wp_get_post_categories();获取自定义分类术语 ID。

您可以将分类名称硬编码到函数中,或者从$args您传入的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;

}
于 2013-06-09T12:56:30.290 回答