Redirect to post if search results return only one post

If your WordPress search results page has only one post in it, this code snippet will automatically redirect you to that particular post.

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

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