Redirect When Search Query Only Returns One Match

Be careful when using this, as users may not expect this functionality.

If there’s only one match for a particular search query, you can save users the hassle of clicking by simply redirecting them to the page/post.

add_action('template_redirect', 'single_result');
function single_result() {
	if (is_search()) {
		global $wp_query;
		if ( $wp_query->post_count == 1 && $wp_query->max_num_pages == 1 ) {
			wp_redirect( get_permalink( $wp_query->posts[0]->ID ) );
			exit;
		}
	}
}

2 thoughts on “Redirect When Search Query Only Returns One Match”

  1. Alma Apatrida

    You should be careful with this function if you have a display limit of posts on the search results page. Lets say you you get a post_count of 11 or 21 and you have a limit of 10 posts per page this function will lead to unwanted results… (redirect to the first search result instead of displaying the last result on a new search results page).
    I suggest to change the second IF statement to the following to avoid this behaviour:
    if (($wp_query->post_count == 1) && ($wp_query->max_num_pages == 1))

  2. Pingback: Useful WordPress code snippets | David Artiss

Leave a Reply

Your email address will not be published. Required fields are marked *