Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/wp-includes/class-wp-query.php
Original file line number Diff line number Diff line change
Expand Up @@ -2539,6 +2539,14 @@ public function get_posts() {
}
}

if ( '' !== $orderby
&& empty( $query_vars['post_status'] )
&& ( '' !== $query_vars['name'] || '' !== $query_vars['pagename'] || '' !== $query_vars['attachment'] )
) {
// Prefer published posts for singular slug/path queries unless a post_status was requested.
$orderby = "{$wpdb->posts}.post_status = 'publish' DESC, $orderby";
}

// Order search results by relevance only when another "orderby" is not specified in the query.
if ( ! empty( $query_vars['s'] ) ) {
$search_orderby = '';
Expand Down
36 changes: 36 additions & 0 deletions tests/phpunit/tests/post/query.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,42 @@ public function test_post_name__in_ordering() {
$this->assertSame( $ordered, wp_list_pluck( $q->posts, 'post_name' ) );
}

/**
* @ticket 47988
*/
public function test_singular_name_query_prefers_published_post_over_draft_with_same_slug() {
$slug = 'shared-slug-47988';

$published_id = self::factory()->post->create(
array(
'post_name' => $slug,
'post_status' => 'publish',
'post_date' => '2023-01-01 00:00:00',
'post_date_gmt' => '2023-01-01 00:00:00',
)
);

// Make the draft newer so post_date DESC would normally pick it first.
$draft_id = self::factory()->post->create(
array(
'post_name' => $slug,
'post_status' => 'draft',
'post_date' => '2023-01-02 00:00:00',
'post_date_gmt' => '2023-01-02 00:00:00',
)
);

$query = new WP_Query(
array(
'name' => $slug,
'post_type' => 'post',
)
);

$this->assertNotEmpty( $query->posts );
$this->assertSame( array( $published_id, $draft_id ), wp_list_pluck( $query->posts, 'ID' ) );
}

public function test_post_status() {
$statuses1 = get_post_stati();
$this->assertContains( 'auto-draft', $statuses1 );
Expand Down
Loading