Wordpress - Loop within a loop?
You can create any number of loops as you wish by creating more WP_Query
objects
$query = new WP_Query($args);
while ($query->have_posts()) :
// initialization for $inner_args & backup the current global $post
$inner_query = new WP_Query($inner_args);
while ($inner_query->have_posts()) :
// do something
endwhile;
// restore the global $post from the previously created backup
endwhile;
EXPLANATION AS REQUESTED
Whenever you call a template tag such as the_title();
, it displays something about the current post in the loop. But how does it know which post is the current post? It is done by reading the information from the global postdata (stored in a global variable $post
)
When using a loop you always use a $query->the_post()
as the first statement. What this function do is set that global data to the next post from the WP_Query
object (the previous contents are lost)
Here when you called the inner loop, the postdata related to the outer loop was getting lost when the inner loop starts working. Then whatever function you use after the end of inner loop is still finding only the inner loop's data.
In the solution you first saved the outer loop's data in another variable before the contents get lost. Then the loop works as it's supposed to be(deleting all outer loop data).
Then when the inner loop's work is done, you now need to use the outer loop's data but it is lost due to the inner loop. This is where you take the previously saved data & replace it. Now you're back to the position you were at when you started the inner loop
You can use WP_Query::reset_postdata() for this too.
$query = new WP_Query($args);
while ($query->have_posts()) :
// initialization for $inner_args & backup the current global $post
$inner_query = new WP_Query($inner_args);
while ($inner_query->have_posts()) :
// do something
endwhile;
// restore the global $post from the previously created backup
$query->reset_postdata();
endwhile;