Display selected category on post page

Lets assume that we have a post which belongs to 2 or more categories and we wish to display, on the post page, the selected category through which we reached to the post page. What is the best method? Keep the category id in a session or in a querystring temporarily? Or any other?

THX

Topic categories posts Wordpress

Category Web


I know this is an old question, but I figured that I'd still weigh in on it.

I think I would do it with a get-request.

Below-written code has not been tested.

So in your category.php-file, then add the id of of the category, that the visitor came from, as such:

$category = get_the_category();
$link_to_the_post = '<a href="' . the_permalink() . '?cat_id=' . $category['ID'] . '">Link to post</a>';

And then check for that parameter in the single.php, as such:

if( !empty( $_GET['cat_id'] ){
  $category = get_the_category( $_GET['cat_id'] );
  echo 'Category: ' . $category['name'];
} else {
  // Fallback, showing all categories (in case the visitor came from some other place)
  the_category(); 
}

To get only the category through which you reached the post, you might use the query vars:

$category_name = get_query_var( 'category_name', 'No Category' );
echo ('Category: ' . $category_name);

The 2nd argument for get_query_var is the default value that is used when no category is returned.

Hope it helps!


I personally like to take all the categories a post is attached to and slap an active class onto them. Here's the code I found and currently use.

/** Active Category **/
// Single Posts only
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 current-cat"><a $2>' . $category->name . '</a>',
    $CatText);
    }
 }
return $CatText;
}
add_filter('wp_list_categories', 'singlePostActiveCat');

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.