Featured Content Gallery
Bad way to reset a query (1 post)

  1. This code in the gallery.php file is wrong:

    <?php $temp_query = $wp_query; ?>
    	    <?php query_posts('category_name=' . get_option('gallery-category') . '&showposts=' . get_option('gallery-items')); ?>
    	      <?php endif; ?>
    	      <?php $wp_query = $temp_query; ?>

    The idea of saving the existing query off to a temp query and then resetting it afterwards is a good one, however the implementation is wrong, and also this is unnecessary.

    The problem with the implementation is that you forgot to declare $wp_query as a global. So if you're being included from inside a function scope, then this won't save the query and won't restore it.

    The main problem though is that WordPress has a built in function to do this for you, which always works everywhere. wp_reset_query() can be called to reset the query to the default, no matter how much you mess with it.

    Change your code to this:

    <?php query_posts('category_name=' . get_option('gallery-category') . '&showposts=' . get_option('gallery-items')); ?>
    	      <?php endif; ?>
    	      <?php wp_reset_query(); ?>

    Notice how I eliminated the use of $temp_query entirely? WordPress makes a safe hidden copy of the original $wp_query, so even if you later call query_posts and change the query, calling wp_reset_query can always restore it back to normal, and it doesn't matter what scope you're in anymore either.


Topic Closed

This topic has been closed to new replies.

About this Plugin

  • Featured Content Gallery
  • Frequently Asked Questions
  • Support Threads
  • Reviews

About this Topic

  • RSS feed for this topic
  • Started 5 years ago by Samuel Wood (Otto)
  • This topic is not resolved
  • WordPress version: 3.2.1