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.

In my homepage loop, I have something that will show which category the post is in. It will say something like "Posted 4 hours ago in Sports by ...". However, when there is no category set, it will omit the category (obviously) and just say "Posted 4 hours ago in by ...". My question is: how do I check if a post belongs to any category in WordPress.

I know that the function in_category() exists, but I would like to avoid having to type out all of the categories, in case they change, or whatever.

Thanks!

share|improve this question

3 Answers 3

You can use is_object_in_term(). Despite name it can also check for taxonomy match if terms are omitted.

is_object_in_term( get_the_ID(), 'category' );
share|improve this answer

use has_category() wp 3.1+ needed though

share|improve this answer

Instead of using get_category() or whatever to echo it out directly, try using get_the_category(), which will simply return an array of the categories. You can then spin through those items and check if they are empty() or not.

Maybe something like:

$categories = get_the_category( $post->ID );
if( is_array(categories) && count($categories) > 0 ) {
  foreach( $categories as $category ) {
    $categories_string .= $category . ", ";
  }
  $categories_string = rtrim(", ", $categories_string);
}

if( !empty( $categories_string ) ) {
  echo "Posted 4 hours ago in {$categories_string} by ...";
} else {
  echo "Posted 4 hours ago by ...";
} 

*untested

share|improve this answer

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.