From 4a9ab59d91f463d7b9021183d0702723fad91c87 Mon Sep 17 00:00:00 2001 From: Peter Wilson Date: Tue, 4 Oct 2022 03:31:04 +0000 Subject: [PATCH] Posts, Post types: Prevent `get_page_by_title()` parsing query twice. In `get_page_by_title()` access the populated `WP_Query::posts` property directly rather than via the `WP_Query::get_posts()` method. This removes unnecessary reprocessing of the query. Follow up to [54234]. Props david.binda, mukesh27, spacedmonkey. Fixes #56721. git-svn-id: https://develop.svn.wordpress.org/trunk@54377 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/post.php | 2 +- tests/phpunit/tests/post/getPageByTitle.php | 22 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/post.php b/src/wp-includes/post.php index 44f00898ab..b4e9f755d7 100644 --- a/src/wp-includes/post.php +++ b/src/wp-includes/post.php @@ -5787,7 +5787,7 @@ function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) 'order' => 'ASC', ); $query = new WP_Query( $args ); - $pages = $query->get_posts(); + $pages = $query->posts; if ( empty( $pages ) ) { return null; diff --git a/tests/phpunit/tests/post/getPageByTitle.php b/tests/phpunit/tests/post/getPageByTitle.php index ece15749ff..1c94987d5f 100644 --- a/tests/phpunit/tests/post/getPageByTitle.php +++ b/tests/phpunit/tests/post/getPageByTitle.php @@ -315,4 +315,26 @@ class Tests_Post_GetPageByTitle extends WP_UnitTestCase { $this->assertSame( $page, $array_a['ID'], 'Should match post id.' ); $this->assertSame( $num_queries, get_num_queries(), 'Should not result in another database query.' ); } + + /** + * Ensure get_page_by_title() only runs the query once. + * + * @ticket 56721 + * @covers ::get_page_by_title + */ + public function test_should_not_run_query_more_than_once() { + $page = self::factory()->post->create_and_get( + array( + 'post_title' => 'some-page', + 'post_type' => 'page', + ) + ); + + // Use the `pre_get_posts` hook to ensure the query is only run once. + $ma = new MockAction(); + add_action( 'pre_get_posts', array( $ma, 'action' ) ); + + get_page_by_title( 'some-page' ); + $this->assertSame( 1, $ma->get_call_count(), 'Query does not run exactly once.' ); + } }