WordPress Snippet: Redirect to single search result

A lot of times when people visit my blog and search for something, I see that most queries only return a single search result. How do I redirect to the single search result by default in WordPress search? – Jerry

You could use the code snippet below to redirect to single search result in WordPress search.

NOTE: To insert the snippet into your WordPress site, we recommend using the Code Snippets plugin instead of modifying your functions.php file.

// Snippet from NibbleGuru.com
function redirect_single_search_result() {

    // Let's first check if this is a WordPress search result page.
    if (is_search()) {
        global $wp_query;

        // Let's check if this is a single search result.
        if ($wp_query->post_count == 1) {

            // Let's redirect to the permalink of the search result.
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
        }
    }
}

// Hook into template_redirect
add_action('template_redirect', 'redirect_single_search_result');

 

Be the first to comment

Leave a Reply