Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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!

share|improve this answer
    
Thank you, this did the trick. I'm setting this as the answer :) –  user27104 Feb 26 '13 at 22:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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