0

After hours of unfruitful Googling, I am asking for your help on this issue.

My objective is to display only 1 category with get_the_category if the category ID matches the ID or slug set in the get_the_category function. Basically I'm asking for something like this: let's say there's a category titled "important". I want to exclude all other categories assigned to the post and only show "important" if the post is within that category. If the post isn't in important, nothing should be displayed. This should be too hard, but I could figure it out.

Here's the closest thing I found to this, but it only displays the first category for the post, no option for manual selection by ID or slug:

<?php 
$category = get_the_category(); 
if($category[0]){
echo '<a href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a>';
}
?>

Thank you for your contributions.

1 Answer 1

0

I think you could do something like this:

$categories = get_the_category();
$displayed_category_id = 1; // set this to the category ID you want to show
$output = '';
if($categories){
    foreach($categories as $category) {
            if ( $displayed_category_id == $category->term_id) {
                  $output .= '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>';
           }
    }
echo $output;
}

It might not be the most efficient code (and it's untested) but it should work...?

You could swap out the slug or category name pretty easily if ID isn't the key you'd like to use. G'luck!

1
  • Thank you, this did the trick. I'm setting this as the answer :)
    – user27104
    Feb 26, 2013 at 22:53

Your Answer

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

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