Single.php Active Category Class

As vancoder notes, a post can have multiple categories and the following code highlights each category, as well as the current month for the post. Add to your theme’s functions.php.

  // Generate active class for categories when viewing single posts
  // Props to Sam Nabi http://samnabi.com/blog/highlight-the-current-category-for-single-posts-in-wordpress
  function singlePostActiveCat ($CatText) {
     global $post;
     if (is_singular()) {
       $categories = wp_get_post_categories($post->ID);
       foreach ($categories as $category_id) {
        $category = get_category($category_id);
        $CatText = preg_replace(
           "/class=\"(.*)\"><a ([^<>]*)>$category->name<\/a>/",
           ' class="$1 active"><a $2>' . $category->name . '</a>',
        $CatText);
        }
     }
  return $CatText;
  }
  add_filter('wp_list_categories', 'singlePostActiveCat');

  // Generate active class for archives when viewing single posts
  // Props to Joshua Abenazer http://wordpress.stackexchange.com/questions/62509/wp-get-archives-get-css-selector-for-current-month
  function singlePostActiveMonth( $ArchiveText ) {
     if (is_singular()){
        $current_month = get_the_date("F Y");
        if ( preg_match("https://wordpress.stackexchange.com/".$current_month.'/i', $ArchiveText ) )
           $ArchiveText = preg_replace('/<li>/i', '<li class="active">', $ArchiveText );
     }
     return $ArchiveText;
  }
  add_filter( 'get_archives_link', 'singlePostActiveMonth' );

Tested on my local dev copy of WP and seems to work.

Leave a Comment