If your moving content around quickly on your WordPress or if your designing a template with no content to fill it, then your going to run in blank query results, Sorry, but you are looking for something that isn’t here. – WordPress default phrase. Now if you don’t have any posts at all then having a default phase is need but if there are posts in your blog and you only want to display a specific category independent from the main loop and the category is doesn’t have any posts then the there is no need to show the box at all. Now I do realized that if the you add a loop to your template then you know it’s there and you’ll make sure there is content to fill it. That being said there is only really two (maybe more) times in which you may want not to show a section if a post category doesn’t exist and/or hasn’t any posts. First is WordPress MU in which a new blog won’t have the category set up and will certainly not have any posts in it. Second when your creating themes for WordPress.org’s Theme Directory or resale and you want to add special features and display methods.
The solution is to through in a if statement to check if the category, in my example: media, exists and if it exists check if there is posts in it. Then and only then will it display the the loop with posts. Okay enough background, I’m a visual person so let me show you the code:
<?php if ( is_term( 'media' , 'category' ) ){ //Does the category exist ?>
<?php query_posts( 'category_name=media' ); if (have_posts()) : //Is there posts in the category ?>
<div class="module">
<div class="module_title">Media</div>
<?php while (have_posts()) : the_post(); //The Loop ?>
<div class="entry">
<p>
<h3 class="media"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<?php the_content(); ?>
</p>
</div>
<?php endwhile; ?>
</ul>
</div>
<?php endif; ?>
<?php }; ?>
WordPress Function used:
is_term() : Returns the index of a defined term, or 0 (false) if the term doesn’t exist.
query_posts() : is used to control which posts show up in The Loop. It accepts a variety of parameters in the same format as used in your URL
have_posts() & post() : both are convenience wrappers around the global $wp_query object
the_content() : Retrieves the post content and echos it.
The work horse of this method it the is_term() function. is_term() has two inputs is_term( $term, $taxonomy ). The $term is require because it can’t see in nothing exists. $taxonomy is where it maybe.