Highlight the post’s categories in the category list

adding a function call to a template file to get the category highlight effect is not always achievable, for instance if the list is shown in the sidebar.
if the standard category widget is used to display the list, marking the current categories – i.e. the categories in the single post – is better done using a filter hook.

add_filter('wp_list_categories','style_current_cat_single_post');
// filter to add the .current-cat class to categories list in single post
function style_current_cat_single_post($output) {
if( is_single() ) :
global $post;
$categories = wp_get_post_categories($post->ID);

foreach($categories as $value) {
if(preg_match('#item-' . $value . '">#', $output)) {
$output = str_replace('item-' . $value . '">', 'item-' . $value . ' current-cat">', $output);
}
}
endif;
return $output;
}

the programming is basicly the same as in the function from page 1.

One Reply to “Highlight the post’s categories in the category list”

Leave a Reply

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