From 13408ddcbdbe77579e78a3239757c344763b4e03 Mon Sep 17 00:00:00 2001 From: Andrew Nacin Date: Tue, 24 Sep 2013 15:52:41 +0000 Subject: [PATCH] Introduce a reset_postdata() method on the WP_Query object, which wp_reset_postdata() now wraps. props ericlewis. fixes #24785. git-svn-id: https://develop.svn.wordpress.org/trunk@25601 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/query.php | 22 +++++++++++++++++----- tests/phpunit/tests/query.php | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/wp-includes/query.php b/src/wp-includes/query.php index 165cb6cb3b..c1ed984837 100644 --- a/src/wp-includes/query.php +++ b/src/wp-includes/query.php @@ -108,17 +108,14 @@ function wp_reset_query() { /** * After looping through a separate query, this function restores - * the $post global to the current post in the main query + * the $post global to the current post in the main query. * * @since 3.0.0 * @uses $wp_query */ function wp_reset_postdata() { global $wp_query; - if ( !empty($wp_query->post) ) { - $GLOBALS['post'] = $wp_query->post; - setup_postdata($wp_query->post); - } + $wp_query->reset_postdata(); } /* @@ -3628,6 +3625,21 @@ class WP_Query { global $wp_the_query; return $wp_the_query === $this; } + + /** + * After looping through a nested query, this function + * restores the $post global to the current post in this query. + * + * @since 3.7.0 + * + * @return bool + */ + function reset_postdata() { + if ( ! empty( $this->post ) ) { + $GLOBALS['post'] = $this->post; + setup_postdata( $this->post ); + } + } } /** diff --git a/tests/phpunit/tests/query.php b/tests/phpunit/tests/query.php index 1c682304d0..75c188a2df 100644 --- a/tests/phpunit/tests/query.php +++ b/tests/phpunit/tests/query.php @@ -57,4 +57,25 @@ class Tests_Query extends WP_UnitTestCase { } } } + + /** + * @ticket 24785 + * + */ + function test_nested_loop_reset_postdata() { + $post_id = $this->factory->post->create(); + $nested_post_id = $this->factory->post->create(); + + $first_query = new WP_Query( array( 'post__in' => array( $post_id ) ) ); + while ( $first_query->have_posts() ) { $first_query->the_post(); + $second_query = new WP_Query( array( 'post__in' => array( $nested_post_id ) ) ); + while ( $second_query->have_posts() ) { + $second_query->the_post(); + $this->assertEquals( get_the_ID(), $nested_post_id ); + } + $first_query->reset_postdata(); + $this->assertEquals( get_the_ID(), $post_id ); + } + + } } \ No newline at end of file