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...
To redirect to a specific part of a page in CodeIgniter, you can make use of anchors and URL fragments. Here's how you can achieve this:In your controller method, after processing the necessary data and preparing it for display, you can set a redirect URL ...
To change the WooCommerce search location, you can modify the search query directly in your theme's functions.php file. You can adjust the search location by using the pre_get_posts action hook to filter the search results based on specific parameters such...