wordpress snippets last updated   : January 29, 2015
we now have 646 snippets

Redirect to post when search query returns single result

wordpress snippet

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.

snippet :  PHPcopy
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 ) );

Did you like this post? If so please share it with your friends. Thanks!

  • http://wpsnipp.com Kevin Chard

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

    • http://www.cliffpaulick.com Cliff Paulick

      Hey, me too now. Sorry. Thanks.

      • http://wpsnipp.com Kevin Chard

        no problem :)

  • Pingback: 29 Wordpress Tweaks to Improve Posts and Pages()

  • Cameron Coleman

    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.

  • Pingback: WordPress Conditional Tags (And Snippets) for Beginners()