Categories
PHP Wordpress

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

You may have noticed that when there is only one search result then user need to click on the title of that result to read more about that post. We can use the below function to redirect user to post page when there is only one search 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.

By Vaseem Ansari

I’m Vaseem, a Software Engineer by Profession, a Traveler, a Foodie by Heart and the founder of VaseemAnsari.com. I started traveling from college days and it has become a part of me now. So when ever I happen to get a chance I pack my bag and am on the roads. You can follow me on these social networks Facebook, Twitter, Google+ and Linkedin.

Leave a Reply

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