Opened 12 years ago
Closed 12 years ago
#24785 closed enhancement (fixed)
Nested loops and resetting post data
| Reported by: |
|
Owned by: |
|
|---|---|---|---|
| Milestone: | 3.7 | Priority: | normal |
| Severity: | normal | Version: | |
| Component: | Query | Keywords: | has-patch needs-testing has-unit-tests |
| Focuses: | Cc: |
Description
While building a custom loop, developers currently only have one function to reset post data - wp_reset_postdata(). This function resets the $post globals and thereby template tags to the original queried object in the $wp_query global. That's great, but not when it comes to nested loops. Using this function when you're deep within a nest of custom loops would mean upon exiting a loop, calling this function resets to the original queried object, although you're still within a loop that has posts related to it.
Attachments (6)
Change History (16)
#5
@
12 years ago
- Keywords needs-testing needs-unit-tests added; dev-feedback removed
- Milestone changed from Awaiting Review to 3.7
.3.diff rehabilitates the whitespace
#7
@
12 years ago
- Keywords has-unit-tests added; needs-unit-tests removed
attachment:24785.unit-tests.diff includes a unit test for postdata resetting while exiting a nested loop.
#8
follow-up:
↓ 9
@
12 years ago
Cool, I like this. Let's have wp_reset_postdata() call this method, then.
In attachment:24785.diff, I suggest we copy the function wp_reset_postdata into a method to the WP_Query class, so upon exiting a nested loop, this method can be called on the previous query object. A la:
<?php /* The loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php // Build custom query $query = new WP_Query( array( 'posts_per_page' => 1 ) ); // Custom query loop if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // Build nested custom query $subquery = new WP_Query( array( 'posts_per_page' => 2 ) ); // Nested custom query loop if ( $subquery->have_posts() ) { while ( $subquery->have_posts() ) { $subquery->the_post(); echo '<li>' . get_the_title() . '</li>'; } } else { // no posts found } /* Restore custom query's post data */ $query->wp_reset_postdata(); echo '<li>' . get_the_title() . '</li>'; } } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); ?> <?php endwhile; ?>