From e8176a19e2b59cc1bf3f284ab442ab84dbc4a5b4 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Sun, 21 Jun 2020 10:34:35 +0000 Subject: [PATCH] Posts, Post Types: Avoid a PHP warning when `get_the_content()` is called outside of the loop. This ensures that `$pages` and other globals are only used after they have been set up in `setup_postdata()`. Follow-up to [44941]. Props tessawatkinsllc, dontdream, spacedmonkey, squarecandy, davidbaumwald, SergeyBiryukov. Fixes #47824. See #42814. git-svn-id: https://develop.svn.wordpress.org/trunk@48114 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-query.php | 2 +- src/wp-includes/post-template.php | 4 +++- tests/phpunit/tests/post/getTheContent.php | 9 +++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-query.php b/src/wp-includes/class-wp-query.php index a1582277e3..06d531c39a 100644 --- a/src/wp-includes/class-wp-query.php +++ b/src/wp-includes/class-wp-query.php @@ -4275,7 +4275,7 @@ class WP_Query { $numpages = $elements['numpages']; /** - * Fires once the post data has been setup. + * Fires once the post data has been set up. * * @since 2.8.0 * @since 4.1.0 Introduced `$this` parameter. diff --git a/src/wp-includes/post-template.php b/src/wp-includes/post-template.php index 164001e716..c2ee232649 100644 --- a/src/wp-includes/post-template.php +++ b/src/wp-includes/post-template.php @@ -282,7 +282,9 @@ function get_the_content( $more_link_text = null, $strip_teaser = false, $post = return ''; } - if ( null === $post ) { + // Use the globals if the $post parameter was not specified, + // but only after they have been set up in setup_postdata(). + if ( null === $post && did_action( 'the_post' ) ) { $elements = compact( 'page', 'more', 'preview', 'pages', 'multipage' ); } else { $elements = generate_postdata( $_post ); diff --git a/tests/phpunit/tests/post/getTheContent.php b/tests/phpunit/tests/post/getTheContent.php index 7bb14a1f93..54b8fe318e 100644 --- a/tests/phpunit/tests/post/getTheContent.php +++ b/tests/phpunit/tests/post/getTheContent.php @@ -75,4 +75,13 @@ class Tests_Post_GetTheContent extends WP_UnitTestCase { $this->assertSame( 'Bang', $found ); } + + /** + * @ticket 47824 + */ + public function test_should_fall_back_to_post_global_outside_of_the_loop() { + $GLOBALS['post'] = self::factory()->post->create( array( 'post_content' => 'Foo' ) ); + + $this->assertSame( 'Foo', get_the_content() ); + } }