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 ) );
Back to top ^

Leave a Reply

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

Join Paulund

  • Access 100s of premium tutorials and downloadable content
  • Members content consists of premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • No ads

Join Paulund