0

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

3 Answers 3

0

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');
1
  • that will set the current-cat class to each one of the categories of the post?
    – vadims
    Apr 29, 2014 at 21:44
0

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!

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.