[wp-hackers] The Post Loop

Ryan Boren ryan at boren.nu
Wed Jan 19 03:19:53 GMT 2005


There have been questions about doing multiple queries and multiple post
loops in a template.  So, let's talk loops.  Here's our basic post loop.

while (have_posts()) : the_post();
  // Do stuff.
endwhile;

have_posts() and the_post() are convenience wrappers around the global
$wp_query object, which is where all of the action is.  $wp_query is
called in the blog header and fed query arguments coming in through GET
and PATH_INFO.  $wp_query takes the arguments and builds and executes a
DB query that results in an array of posts.  This array is stored in the
object and also returned back to the blog header where it is stuffed
into the global $posts array (for backward compat with old post loops).

Once we finish with the blog header and descend into the template, we
arrive at our post loop.  have_posts() simply calls into $wp_query-
>have_posts() which checks a loop counter to see if there are any posts
left in the post array.  the_post() calls $wp_query->the_post() which
advances the loop counter and sets up the global $post variable as well
as all of the global post data.  Once we have exhausted the loop,
have_posts() will return false and we are done.

Now, if you want to loop through the same query a second time, call
rewind_posts().  This will reset the loop counter and allow you to do
another loop.

rewind_posts();

while (have_posts()) : the_post();
  // Do other stuff.
endwhile;

What if you want to use a different query?  If you are finished with the
posts in the original query, you can reuse the $wp_query object by
calling query_posts() and then looping back through.  query_posts() will
perform a new query, build a new posts array, and reset the loop
counter.

// Get the last 10 posts in the special_cat category.
query_posts('category_name=special_cat&showposts=10');

while (have_posts()) : the_post();
  // Do special_cat stuff.
endwhile;

If you need to keep the original query around, you can create a new
query object.

$my_query = new WP_Query('category_name=special_cat&showposts=10');

while ($my_query->have_posts()) : $my_query->the_post();
  // Do stuff.
endwhile;

As you can see, you cannot use the global have_posts() and the_post()
since they use $wp_query.  Instead, call into your new $my_query object.

Ryan





More information about the hackers mailing list