Post Pic

WordPress tip: Storing $wp_query for future use

When working with WordPress queries, it may be very useful to be able to clone, store and restore $wp_query. This is exactly what we’re going to see in this recipe.

With PHP 5, objects can be cloned using the clone operator. The code below is pretty self-explanatory:

 // saving the query
 <?php $temp_query = clone $wp_query; ?>

 <!-- Do stuff... -->  

 //listing out featured articles
 <?php query_posts('category_name=featured&showposts=3'); ?>

 <?php while (have_posts()) : the_post(); ?>
   <!-- Do special_cat stuff... -->

 <?php endwhile; ?>

 // restoring the query so it can be later used to display our posts
 <?php $wp_query = clone $temp_query; ?>

This code comes from an article entitled Multiples WordPress loops explained, written by Cristian Antohe at Cats Who Code.

9 Responses

Jul 10 2009 13:43

Hmm Interesting. This could be useful if you needed to query the same query in multiple spots on the page, but wasn’t part of the main loop.

Thank you for this.

Jul 10 2009 16:05

I don’t see the benefit in the cloning, and would be concerned that it is not php4 compatible. I’ve never had a problem using a plain variable reference such as “$temp_query = $wp_query;”

Jul 11 2009 03:03

This is cool, no wiget needed. But may I ask how to only show one post with any ID? For example, how to show post ID=1 for the feature post?

Jul 12 2009 07:08

That’s very useful for theme developers. I may use it in one of my themes sometime.

Jul 13 2009 04:28

This trick is useful when we need EXTRA ORDINARY Themes ;)

Jul 20 2009 22:38

I agree with TJ, what is the benefit to this as opposed to simply, “$temp_query = $wp_query;”? (which I have used several times in the past).

Lew

Aug 12 2009 17:29

why not just use wp_reset_query() ?

Oct 27 2009 16:07

Indeed.

wp_reset_query() does the job to reset query_posts().

And about cloning…. most shared hosts I know still (!) don’t support PHP5. And the clone function simply isn’t neccecary.

A simple $tmpQuery = $wp_query; does the same job. No need for cloning.

But ofcourse above all…. You shouldn’t use query_posts() at all within a loop. WordPress comes with a built-in function especially for loops-in-loops for which you don’t need ANY rewinding, resetting, cloning or temporary saving.

It’s called WP_Query();

Read all about it here:
http://codex.wordpress.org/Function_Reference/WP_Query

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required