Categories
Wordpress

Redirect to post when search query returns single result

To avoid the list of just a single search result, you can add the following code in your theme’s function.php file.

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

This code will also avoid the automatic redirection in case of many search results split in pages and in the last page there is just a single result.