[wp-hackers] Loop Within A Loop

Andrew Nacin wp at andrewnacin.com
Tue Jul 20 19:52:34 UTC 2010


On Tue, Jul 20, 2010 at 3:46 PM, Devin Dixon <devin at tayloegray.com> wrote:

> Hey everyone,
> I am having a problem where I need to call a loop within a loop.The
> code looks somethign like this
>
>  if ( have_posts() ) while ( have_posts() ) : the_post();
>
>        while ( $loop->have_posts() ) : $loop->the_post();
>
>            $wp_query= new WP_Query( array( 'post_type' =>
> "$post_type", 'posts_per_page' => $post_per_page , 'post_parent' =>
>                 $parent_post , 'author' => "$author" ) );
>
>  while ($wp_query->have_posts()) : $wp_query->the_post();
>
> ?>
>
> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent
> Link to <?php the_title_attribute(); ?>"><?php        the_title();
> ?></a>
>
> <?php
>
>        endwhile;
>
>         endwhile;
>
> endif;
>
> The problem is, the class WP_QUERY automatically makes everything
> global. Is there a way where I can call the WP_QUERY object and
> retrieve it values without it affecting the other loop?


You have three loops there, with one unused... One isn't closed, and the if
statement isn't properly opened, so it also can't be closed.

That said, one option is to call the_post() again on the main loop. Or use a
variant technique for sub loops.


More information about the wp-hackers mailing list