Highlight the post’s categories in the category list

highlighting the categories of a post in single post view is a useful trick to allow the viewer to find related posts.

there are plugins available which extend the functionality of the standard category widget to do this.

sometimes, however, it can be desirable to have the same feature with a function that you can use like you would use ‘wp_list_categories();’ – exactly with the same arguments.

/* hi_list_categories() to highlight the current categories of a post in single.php;
uses the arguments in the same way as wp_list_categories();
alchymyth 2010 / www.transformationpowertools.com/wordpress */
function hi_list_categories($args) {
//following section is extracted from http://phpxref.com/xref/wordpress/wp-includes/category-template.php.source.html#l389
$defaults = array(
'show_option_all' => '',
'orderby' => 'name',
'order' => 'ASC',
'show_last_update' => 0,
'style' => 'list',
'show_count' => 0,
'hide_empty' => 1,
'use_desc_for_title' => 1,
'child_of' => 0,
'feed' => '',
'feed_type' => '',
'feed_image' => '',
'exclude' => '',
'exclude_tree' => '',
'current_category' => 0,
'hierarchical' => true,
'title_li' => __( 'Categories' ),
'echo' => 1,
'depth' => 0
);
$r = wp_parse_args( $args, $defaults );
if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) {
$r['pad_counts'] = true;
}
if ( isset( $r['show_date'] ) ) {
$r['include_last_update_time'] = $r['show_date'];
}
if ( isset( $r['echo'] ) ) {
$echo_or_return = $r['echo'];
} ; $r['echo'] = 0;
if ( true == $r['hierarchical'] ) {
$r['exclude_tree'] = $r['exclude'];
$r['exclude'] = '';
}
extract( $r );
//end of extracted code
global $post;
// highlighting only for single post view
if(is_single()) :
$categories = wp_get_post_categories($post->ID);
foreach ($categories as $catid) {
$cat = get_category($catid);
$cats[] = $cat->cat_ID;
}
$cats_list = wp_list_categories( $r );
foreach($cats as $value) {
if(preg_match('#-item-' . $value . '">#', $cats_list)) {
$cats_list = str_replace('item-' . $value . '">', 'item-' . $value . ' current-cat">', $cats_list);
}
}
if($echo_or_return == 1) { echo $cats_list; }
else { return $cats_list; } ;
else :
//use default category list if not single post view
wp_list_categories( $args );
endif;
} //end of function hi_list_categories();

in the same way, as you would have used ‘wp_list_categories();’ you can now use ‘hi_list_categories();’ which will add the class ‘.current-cat’ to each of the categories of the post in single post view.

2 Replies to “Highlight the post’s categories in the category list”

  1. I have noticed you don’t monetize your website, don’t waste your traffic,
    you can earn additional bucks every month because you’ve got high quality
    content. If you want to know how to make extra bucks, search for:
    Mrdalekjd methods for $$$

Leave a Reply to SEO Services and Consultation Cancel reply

Your email address will not be published. Required fields are marked *