When there is only one search result, it can be a little annoying having to click the one and only search result. In WordPress, there’s a really easy way to redirect the user to the one and only search result that was found for their query. This will save your user the annoyance of having to click the only result found and will make their user experience much smoother.

Place this code into your theme’s functions.php file or create a plugin with this code in it:

function redirect_single_result() {
    // Check if we are on the search results page.
    if (is_search()) {
        global $wp_query;
		// Check if there's only 1 blog posts in the query.
		// If there's only one then it means only one blog post was found.
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); // Redirect to the only blog post that was found.
        }
    }
}
add_action('template_redirect', 'redirect_single_result');

The above code adds a function called redirect_single_result to the template_redirect hook. This hook is called before any content is generated. The function redirect_single_result will be called on every page. The function first checks if the current page is the search results page. If it is, then it checks if there’s only one blog post for the search query. And if there’s only one blog post, then it redirects the user to the permalink of the first and only blog post that was found.

Pin It on Pinterest

Share This