diff --git a/src/wp-includes/post.php b/src/wp-includes/post.php index 17abaf8558c05..cd4a32093f911 100644 --- a/src/wp-includes/post.php +++ b/src/wp-includes/post.php @@ -5775,14 +5775,14 @@ function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) { */ function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) { $args = array( - 'post_title' => $page_title, + 'title' => $page_title, 'post_type' => $post_type, 'post_status' => get_post_stati(), 'posts_per_page' => 1, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'no_found_rows' => true, - 'orderby' => 'ID', + 'orderby' => 'post_date ID', 'order' => 'ASC', ); $query = new WP_Query( $args ); diff --git a/tests/phpunit/tests/post/getPageByTitle.php b/tests/phpunit/tests/post/getPageByTitle.php index a09599c289c9a..ece15749ffdf6 100644 --- a/tests/phpunit/tests/post/getPageByTitle.php +++ b/tests/phpunit/tests/post/getPageByTitle.php @@ -5,6 +5,41 @@ * @covers ::get_page_by_title */ class Tests_Post_GetPageByTitle extends WP_UnitTestCase { + + /** + * Generate shared fixtures. + * + * These are not used in the tests but are rather used to populate the + * posts table and ensure that the tests return the correct post object + * by design rather than through chance. + */ + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { + // Fill the database with some pages. + $factory->post->create_many( + 2, + array( + 'post_type' => 'page', + ) + ); + + // Fill the database with some attachments. + $factory->post->create_many( + 2, + array( + 'post_type' => 'attachment', + ) + ); + + // Fill the database with some test post types. + register_post_type( 'wptests_pt' ); + $factory->post->create_many( + 2, + array( + 'post_type' => 'wptests_pt', + ) + ); + } + /** * @ticket 36905 */ @@ -43,6 +78,53 @@ public function test_should_match_top_level_page() { $this->assertSame( $page, $found->ID ); } + /** + * @ticket 36905 + * @ticket 56609 + */ + public function test_should_be_case_insensitive_match() { + $page = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => 'Foo', + ) + ); + + $found = get_page_by_title( 'foo' ); + + $this->assertSame( $page, $found->ID ); + } + + /** + * Test the oldest published post is matched first. + * + * Per the docs: in case of more than one post having the same title, + * it will check the oldest publication date, not the smallest ID. + * + * @ticket 36905 + * @ticket 56609 + */ + public function test_should_match_oldest_published_date_when_titles_match() { + self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => 'foo', + ) + ); + + $old_page = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_title' => 'foo', + 'post_date' => '1984-01-11 05:00:00', + ) + ); + + $found = get_page_by_title( 'foo' ); + + $this->assertSame( $old_page, $found->ID ); + } + /** * @ticket 36905 */