I'm trying to exclude all the posts that doesn't have a category assigned to from the main loop, i searched everywhere and i found a billion ways to exclude some categories or filter from specific category but not what i need to do, is it possibile?

1 Answer 1


Hi @Raffaele:

The function wp_get_object_terms(...) can provide you with the information you need. I've written a has_category($post_id) function that can be used in the loop like this:

<?php while ( have_posts() ) : the_post(); ?>
   <?php if (has_category($post->ID)): ?>
      <p><?php the_title(); ?></p>
   <?php endif; ?>
<?php endwhile; ?>

And here is the has_category() function:

function has_category($post_id) {
  $has_category = false;
  $terms = wp_get_object_terms($post_id,'category');
  if (is_array($terms)) {
    foreach($terms as $index => $term)
      if ($term->slug=='uncategorized')
    $has_category = (count($terms)>0);
  return $has_category;

Note that my has_category() function treats posts with the 'uncategorized' category as having no category. There are probably more performant ways to accomplish this but what you see above should work.


  • What about query_posts with category__in?
    – t31os
    Feb 10, 2011 at 16:39
  • @t31os - Probably. There are many roads that lead to Rome, this was just the one I chose to write about. :) Feb 10, 2011 at 22:51
  • 1
    The downside to this method is that you don't always have the same number of posts per page. When you ignore a post you don't add an extra one at the end of the page.
    – Jan Fabry
    Feb 11, 2011 at 15:28
  • @Jan Fabry - True. Feb 11, 2011 at 15:39

Your Answer

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