0

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

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:

<?php
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')
        unset($terms[$index]);
    $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.

-Mike

  • 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
  • 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 '11 at 15:28
  • @Jan Fabry - True. – MikeSchinkel Feb 11 '11 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy