Redirect users after search if there was only one result found

Search functionality is a must have if you’re dealing with a larger number of articles. If you are writing on a daily basis, imagine the number of articles scattered across different categories. If you publish only 3 short articles per day, there will be over a thousand different titles in your database after the first year. Now imageine yourself coming to the site for the first time while looking for something specific – you will want to search for it.

By default, WordPress will search through post titles, tags and of course the content. So, if searching for a word or a specific phrase, it will probably found dozens of posts and pages which contain the query. But what if there was only one search result?

If someone was searching for a very specific phrase or an entire sentence, chances are there will be only few or maybe only one result. If there is only one result found, redirecting a user to the search results page is quite unnecessary. Instead, why wouldn’t you take that user directly to the post/page found in the result?

Let’s see how to do that:

  1. Open functions.php
  2. Copy this code and paste it at the end of the file:
  3. add_action(‘template_redirect’, ‘redirect_search_result);
    function redirect_search_result() {
    if (is_search()) {
    global $wp_query;
    if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
    wp_redirect( get_permalink( $wp_query->posts[‘0’]->ID ) );
    exit;
    }
    }
    }

  4. Save changes

You have prepared your WordPress for new functionality. After you have saved changes, every time a user searches for something which will return only one results, that user will be redirected directly to the post/page.

Even if it seems like nothing much, we’re sure your visitors will like you for saving them a click of button. Saving a click here and a click there will result in a better user experience and that’s probably something you want on your website, isn’t it?

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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