Marc Blase

WordPress custom queries need resetting, y’hear?

So, as I often do when building WP themes, I make custom queries. Something along the lines of:

$custom_query = new WP_Query('category_name=category_name&showposts=3');
while ($custom_query->have_posts()) : $custom_query->the_post();
// Do fancy layout here
endwhile;
if(is_page())
 // Do page stuff - DOESN'T WORK!!!

This is all well and good, but if you are using conditionals below this custom query, as we are in the example above, they will not work. At all. So, WordPress devs knew we’d need a construct for this. If you haven’t met, let me introduce you to wp_reset_query(). Add it after you close your loop and you’re all set to is_page(), is_archive(), etc.

$custom_query = new WP_Query('category_name=category_name&showposts=3');
while ($custom_query->have_posts()) : $custom_query->the_post();
// Do fancy layout here
endwhile;
wp_reset_query();
// Do conditionals ...
if (is_page())
    // Do page stuff - Totally works!
Published on November 18, 2011