WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 1 down vote accepted

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.


share|improve this answer
What about query_posts with category__in? – t31os Feb 10 '11 at 16:39
@t31os - Probably. There are many roads that lead to Rome, this was just the one I chose to write about. :) – MikeSchinkel Feb 10 '11 at 22:51
thanks for the quick response, it worked great! – user3075 Feb 11 '11 at 15:13
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 '11 at 15:28
@Jan Fabry - True. – MikeSchinkel Feb 11 '11 at 15:39

Your Answer


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