Add current_cat class on wp_list_categories when I'm on single with custom taxonomy

浪尽此生 提交于 2019-12-13 21:23:07

问题


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.

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.

Is it even possible ?


回答1:


You need to use get_the_terms( $id, $taxonomy ); instead of wp_get_post_categories(); for getting custom taxonomy term IDs.

You can hardcode taxonomy name into the functon or get it from the $args you passed into wp_list_categories( $args );.

Final code:

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;

}


来源:https://stackoverflow.com/questions/15744615/add-current-cat-class-on-wp-list-categories-when-im-on-single-with-custom-taxon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!