Make WordPress Core

Changeset 54377


Ignore:
Timestamp:
10/04/2022 03:31:04 AM (2 years ago)
Author:
peterwilsoncc
Message:

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.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/post.php

    r54320 r54377  
    57885788    );
    57895789    $query = new WP_Query( $args );
    5790     $pages = $query->get_posts();
     5790    $pages = $query->posts;
    57915791
    57925792    if ( empty( $pages ) ) {
  • trunk/tests/phpunit/tests/post/getPageByTitle.php

    r54271 r54377  
    316316        $this->assertSame( $num_queries, get_num_queries(), 'Should not result in another database query.' );
    317317    }
     318
     319    /**
     320     * Ensure get_page_by_title() only runs the query once.
     321     *
     322     * @ticket 56721
     323     * @covers ::get_page_by_title
     324     */
     325    public function test_should_not_run_query_more_than_once() {
     326        $page = self::factory()->post->create_and_get(
     327            array(
     328                'post_title' => 'some-page',
     329                'post_type'  => 'page',
     330            )
     331        );
     332
     333        // Use the `pre_get_posts` hook to ensure the query is only run once.
     334        $ma = new MockAction();
     335        add_action( 'pre_get_posts', array( $ma, 'action' ) );
     336
     337        get_page_by_title( 'some-page' );
     338        $this->assertSame( 1, $ma->get_call_count(), 'Query does not run exactly once.' );
     339    }
    318340}
Note: See TracChangeset for help on using the changeset viewer.