Redirect to page if only 1 result is found

Use this code to redirect a viewer directly to the page, if only 1 search result is found. Useful when people know exactly the model number they want for an ecom store.

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 ) );
        }
    }
}
Click to Copy