How to Redirect to Post if Search Result Returns Only One Match

When someone searches your blog using WordPress built-in search engine, the results are displayed as a list. Wouldn’t it be nice if we can redirect the visitor directly to the post when there is only one match in the search list? Here is a snippet can do just like that.

Copy and paste the following code snippet into your functions.php file, or your own plugin.

// Redirect to post when there is only one post in search results
function redirect_search_to_single_post() {
    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;
        }
    }
}

add_action('template_redirect', 'redirect_search_to_single_post');