WordPress Loop Within A Loop

This was really complicated until I read http://codex.wordpress.org/The_Loop#Multiple_Loops_Example_2. What I was doing wrong was I forgot to do this:

Note: In PHP 5, objects are referenced with the “= clone” operator instead of “=” like in PHP 4. To make Example 2 work in PHP 5 you need to use the following code: –http://codex.wordpress.org/The_Loop#Multiple_Loops_Example_2

here’s the code:

$the_query_new = new WP_Query( $args );

// The Loop
while ( $the_query_new->have_posts() ) : $the_query_new->the_post();
$temp_query = clone $the_query_new;  // store it
//loop blah blah

//A Loop Within A Loop

$the_query_new = new WP_Query($args);

while ($the_query_new->have_posts()) : $the_query_new->the_post();
// -- your new loop -- //
echo "hi ";
endwhile;
//if (isset($the_query_new)) $the_query_new = $temp_query;} // restore loop
$the_query_new = clone $temp_query; //restore loop

endwhile;

// Reset Post Data
wp_reset_postdata();
Advertisements