Skip to content

Query Loop block does not display search results in order of relevance #39285

@JakePT

Description

@JakePT

Description

Normally WordPress search results are sorted by relevance, using relevance for orderby in the query. The Query Loop block however enforces date as the orderby argument by default when "Inherit query from template" is selected. This means that search results are only displayed in date order if the results are displayed using the Query Loop block, as they are in Twenty Twenty-Two.

Step-by-step reproduction instructions

  1. Create a post with a particular word in the title.
  2. Create a second newer post with the same word in the content.
  3. Using Twenty Twenty Twenty-One, or any non-block theme, search for that word. The older post with the word in the title should appear at the top, since it's more relevant due to having the word in the title.
  4. Using Twenty Twenty-Two, or any theme that uses the Query Loop block for search results, and search for the same word. The newer post will appear at the top, even though it's less relevant. This is because it's the most recent post.

A workaround is to use the pre_get_posts hook to correct the order (props @felipeelia):

add_action(
	'pre_get_posts',
	function( $query ) {
		if ( $query->is_main_query() && $query->is_search() ) {
			$query->set( 'orderby', 'relevance' );
			$query->set( 'order', 'DESC' );
		}
	}
);

Screenshots, screen recording, code snippet

No response

Environment info

WordPress 5.9.1
Twenty Twenty-Two 1.1
Gutenberg is not installed.

Please confirm that you have searched existing issues in the repo.

Yes

Please confirm that you have tested with all plugins deactivated except Gutenberg.

Yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions