Sub-loop / nested loops Best Practices

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.

Read More

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?

Related posts

Leave a Reply

1 comment

  1. First see When should you use WP_Query vs query_posts() vs get_posts()?

    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.

    Yes, it’s commonly referred to as “main loop”. But “loop” in general can refer to iterating through any set of posts.

    Or is $subQuery->have_posts() safe to use (ie: read only)?

    Yes, it’s just a way to check if loop has posts that had not been iterated yet.

    What about ->the_post()? Does it affect The Loop globals?

    Yes, it does. After loops that use the_post() (function or method) you need to call wp_reset_postdata() (or more global wp_reset_query() if you was messing with main loop) to cleanup global variables.

    What’s the best practice for iterating through elements of a nested sub-loop that will not interfere with The Loop?

    This depends if you need to use template tags that rely on global $post, so there are several approaches. You can iterate through new WP_Query object and cleanup afterwards or just fetch array with get_posts() and do something with it.