search ]

Auto Redirect to Post on Single Search Result

This snippet causes a redirect to the post when a WordPress search returns only one result, instead of displaying the search results page as usual.

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

add_action('template_redirect', 'single_result');

For more on WordPress search optimization, see Prevent Search Engines from Indexing Search Results.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo