Redirect to post when search query returns single result

Adding this snippet to the functions.php of your wordpress theme will redirect your search to the post automatically when wordpress only returns a single search result.

add_action('template_redirect', 'single_result');
function single_result() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );

Comments  Leave a Reply

  1. Thanks!

  2. 12 Not-So-Obvious WordPress Tweaks to Improve Posts and Pages - WPMU DEV March 27, 2015 at 8:10 am

    […] really like this one – thanks WP Snipp! When a user searches your website and there is only one result the user is taken straight to the […]

  3. WordPress Conditional Tags (And Snippets) for Beginners March 4, 2015 at 11:52 pm

    […] [Source] […]

  4. Cameron Coleman July 26, 2013 at 6:31 pm

    Nice code but I would make one improvement… change

    if ($wp_query->post_count == 1) to
    if ($wp_query->found_posts == 1)
    The original code breaks pagination when there is only one post left on the next page and redirects to it instead of showing it. eg. If a post archive is set to show 10 post per page and 11 results are returned then instead of showing the last post it redirects to it.

  5. 29 Wordpress Tweaks to Improve Posts and Pages October 18, 2011 at 9:03 am

    […] [Source: WPSNIPP] […]

  6. Your sample worked fine for me, everything appears to work working.

    1. Cliff Paulick July 25, 2011 at 6:37 pm

      Hey, me too now. Sorry. Thanks.

      1. no problem 🙂

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!