Quick Tip: Highlight Current Category Menu Item for WordPress Single Post

written by aext on May 26, 2010 in Quick Tips and WordPress with 26 comments

From version 2.0, WordPress automatically added highlighting categories feature by adding current-cat class name in the category menu item when viewing that category. However, WordPress forgot to do the same on a single post viewing. Here are some quick tips help us to dynamically highlight the category menu item(s) when viewing a single post which belongs to that category(ies).

Using plugin


1. WordPress Plugin: Show Active Category
This is a very easy way to do category highlighting on WordPress single post. All you need is downloading this WordPress Plugin: Show Active Category and activate it:

  1. Download this plugin, un-pack it, and upload it to WordPress plugins folder.
  2. Activate the plugin
  3. You will notice the menu in WordPress backend: Show Active Category (while browsing a post)
  4. Add this class name to your css file: .active_category{ ... }

Thanks Max for this tip, and Screenshine for this helpful plugin.

2. Kahi’s Highlight Used Categories

This plugin works in the same way with that one above. Furthermore, it allows to highlight categories when you’re browsing a post (or even a page) filed under some categories, these are (in the category list) marked by adding specific class.

Classes used-cat and eventually used-cat-parent are added to the particular list (list-items) in each category-list (wp_list_category()).

Thanks Kahi for this plugin.

Code Customization


If you are friendly with WordPress code, you can easily to do highlighting by overriding the wp_list_categories() function. Copy and paste these code to your functions.php file:

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);

	       // Find cat-item-ID in the string
	       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');

Then use css to style it as we usually do with default highlighting current category when viewing it.

li.current-cat { ...put your styles here...}

Thanks Ade for such awesome stuff!