Redirect to page if only 1 result is found

25 May 2023

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 ) );

Was this article helpful?



Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy