Highlight the current category for single posts in WordPress

When you browse a category in WordPress, a current-cat class is added to the category’s list item in the wp_list_categories menu. This is really useful for styling your menu so readers have a visual cue of where they are in your blog.

But when viewing an individual post, the current-cat class doesn’t get generated. To generate it when your visitors are reading a single post, insert the following code in your theme’s functions.php file.

// Generate the current-cat class when viewing single posts
class singlePostCurrentCat {
  function wp_list_categories ($text) {
    global $post;
      if (is_singular()) {
        $categories = wp_get_post_categories($post->ID);
        foreach ($categories as $category_id) {
          $category = get_category($category_id);
          $text = preg_replace(
            "/class=\"(.*)\"><a ([^<>]*)>$category->name<\/a>/",
            ' class="$1 current-cat"><a $2>' . $category->name . '</a>',
          $text);
        }
      }
    return $text;
  }
}
add_filter('wp_list_categories', array('singlePostCurrentCat','wp_list_categories'));

(Adapted from Kahi’s Highlight Used Categories plugin.)


  • http://twitter.com/ryanpaonessa Ryan Paonessa

    awesome. thanks man