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 ) );
			}
		}
	}
}

Stay in touch

For a daily email update, click HERE or enter your email and stay on top of things by receiving weekly news in your inbox.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>