Redirect to post if search results return only one post

a minute read

Although WordPress traditional search doesn’t provide search quality as good as Google Custom Search, however many WordPress users still use it, as it is the default search and you don’t need to customize your theme to add search feature on your blog.

Recently, a friend of mine asked me about redirecting to a post when search results have only one item. Such needs may differ from site to site, it all depends on your audience and what features you want to add to your site for their ease. In this post, we will know how to redirect to the post if our search results return only a single post.

We will add a code that tells the WordPress search query to redirect to the first (or the only) post in the search results when it returns only one match. To implement this, just add this short snippet to the functions.php of your WordPress theme just below the closing PHP tag, i.e. ?> and save the changes:

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

That’s it. If your search results page has one post in it, it will redirect to that particular post by itself from now.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To do a simple redirect in Laravel, you can use the redirect() function provided by the framework. This function allows you to redirect the user to a new URL or route.Here's an example of how you can perform a redirect in Laravel: return redirect('/new...
The native WordPress search feature by default displays pages in the search results. The feature is meant for site-wide searches, but could be annoying to users who just want to display only the posts in the search results. I have this small code snippet worki...
The default WordPress search is the only thing that used to annoy me a lot and I wasn’t using it on any of my WordPress sites. There are a number of reasons back then to stop using WordPress search feature, and the best one for me was it throwing unrelated lin...