Categories
PHP Wordpress

WordPress : Redirect To Post Page When Search Query Returns Single Result

If your website have lots of links and people often use search box to search what they are looking for. When there is only one search result then user need to click on the title of that result to read more about that post. A solution here is why we need to show the search results page when there are only one search result.

You may use below simple php code in your WordPress theme’s functions.php file to redirect your search to the post automatically when WordPress only returns a single search result.


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