Paulund
2012-10-09 #wordpress

Redirect To Post If Search Results Return One Post

Wordpress has a built in search functionality which allows your visitor to easily search for posts on the blog. It can search for keywords in the post title and in the post content. When a search is performed Wordpress will use the search.php file to display you the results. You can customise this page to display the entire list of posts returned from the Wordpress database. The problem is that if Wordpress returns only one post in the search results it will still take you to the search.php file and display a list of posts, well the one post. Below is a Wordpress snippet you can add to your functions.php file to check how many posts are returned by the search, if it returns one post then performs a redirect to the post.


add_action('template_redirect', 'redirect_single_post');
function redirect_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;
        }
    }
}