I’m trying sort through the morass that is WP documentation, and just need someone to clear up the use of the term “The Loop” and how it relates to subloops.
My understanding of “The Loop” is that there is, and should only ever be, ONE “The Loop” per page/post – and that The Loop is responsible for iterating through that page/post/archive’s content.
In particular the_post() will populate a number of global variables with the relevant data extracted from the current position of the query in the main Loop.
I also believe I understand that whenever creating a sub-loop (say you want to get a list of all child posts of each post listed in a category archive), you should use a new instance of the WP_Query object, as in: $subQuery = new WP_Query($args);
Where I run into confusion with the Codex docs is in the documentation of Wp_Query, specifically $subQuery->have_posts() and $subQuery->the_post().
The documentation lists “to be used when in The Loop” for both of those methods, implying (to me) that they manipulate global variables that would affect The (outer) Loop. Is this the case? Or is $subQuery->have_posts() safe to use (ie: read only)? What about ->the_post()? Does it affect The Loop globals?
What’s the best practice for iterating through elements of a nested sub-loop that will not interfere with The Loop?
First see When should you use WP_Query vs query_posts() vs get_posts()?
Yes, it’s commonly referred to as “main loop”. But “loop” in general can refer to iterating through any set of posts.
Yes, it’s just a way to check if loop has posts that had not been iterated yet.
Yes, it does. After loops that use
the_post()
(function or method) you need to callwp_reset_postdata()
(or more globalwp_reset_query()
if you was messing with main loop) to cleanup global variables.This depends if you need to use template tags that rely on global
$post
, so there are several approaches. You can iterate through newWP_Query
object and cleanup afterwards or just fetch array withget_posts()
and do something with it.