From 96649a5ad1a80cd8aaea15b955a48e292c406135 Mon Sep 17 00:00:00 2001 From: Andrew Ozz Date: Sat, 4 May 2019 20:59:11 +0000 Subject: [PATCH] Fix `setup_postdata()` to set the (inside the loop) globals before `the_post` action is fired. Follow-up from #42814 and [44941]. Props david.binda, spacedmonkey, boonebgorges, birgire, jorbin, azaozz. Fixes #47114 for trunk. git-svn-id: https://develop.svn.wordpress.org/trunk@45285 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-query.php | 22 ++++++++++----------- tests/phpunit/tests/query/setupPostdata.php | 22 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/wp-includes/class-wp-query.php b/src/wp-includes/class-wp-query.php index 953f917d27..f1168504bb 100644 --- a/src/wp-includes/class-wp-query.php +++ b/src/wp-includes/class-wp-query.php @@ -4208,6 +4208,17 @@ class WP_Query { $more = $elements['more']; $numpages = $elements['numpages']; + /** + * Fires once the post data has been setup. + * + * @since 2.8.0 + * @since 4.1.0 Introduced `$this` parameter. + * + * @param WP_Post $post The Post object (passed by reference). + * @param WP_Query $this The current Query object (passed by reference). + */ + do_action_ref_array( 'the_post', array( &$post, &$this ) ); + return true; } @@ -4298,17 +4309,6 @@ class WP_Query { $multipage = 0; } - /** - * Fires once the post data has been setup. - * - * @since 2.8.0 - * @since 4.1.0 Introduced `$this` parameter. - * - * @param WP_Post $post The Post object (passed by reference). - * @param WP_Query $this The current Query object (passed by reference). - */ - do_action_ref_array( 'the_post', array( &$post, &$this ) ); - $elements = compact( 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' ); return $elements; diff --git a/tests/phpunit/tests/query/setupPostdata.php b/tests/phpunit/tests/query/setupPostdata.php index 5a20862bcc..34a99d68a9 100644 --- a/tests/phpunit/tests/query/setupPostdata.php +++ b/tests/phpunit/tests/query/setupPostdata.php @@ -9,6 +9,8 @@ class Tests_Query_SetupPostdata extends WP_UnitTestCase { protected $global_data = array(); + protected $pages_global; + public function setUp() { parent::setUp(); return; @@ -416,4 +418,24 @@ class Tests_Query_SetupPostdata extends WP_UnitTestCase { } } + /** + * @ticket 47114 + * + * setup_postdata() should set the globals before `the_post` action is fired. + */ + public function test_the_post_action() { + $post = self::factory()->post->create_and_get(); + add_action( 'the_post', array( $this, 'the_post_action_callback' ) ); + + setup_postdata( $post ); + + $this->assertEquals( $GLOBALS['pages'], $this->pages_global ); + } + + /** + * Helpers + */ + public function the_post_action_callback() { + $this->pages_global = $GLOBALS['pages']; + } }