Exclude posts without category from loop

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

tech