Search code examples
wordpresswoocommercecode-snippetswordpress-shortcode

Redirect to a specific page when WooCommerce product search returns "no product found"


In Woocommerce I am trying to use the following code snippet to redirect to a specific page of my site instead of showing "no result found" on an empty product search.

Now the shortcode [insert page id="99"] doesn't work, and displays [insert page id="99"] as plain text. If I use shortcode any shortcode like '[recent_products per_page="4"]' it displays products.

remove_action( 'woocommerce_no_products_found', 'wc_no_products_found' );
add_action( 'woocommerce_no_products_found', 'show_products_on_no_products_found', 20 );
function show_products_on_no_products_found() {
    echo '<h4>' . __( 'Are u looking for this?', 'domain' ) . '</h4>';
    echo do_shortcode( '[insert page id="99"]' );
}

But I want is to redirect to a specific WordPress page which post id is 99.

How to redirect user to a specific page when a product search returns "no product found"?


Solution

  • Using template_redirect hook, you can redirect user to a specific page when there is "no results found" on a product query search, like:

    add_action( 'template_redirect', 'no_products_found_redirect' );
    function no_products_found_redirect() {
        global $wp_query; 
        if( isset($_GET['s']) && isset($_GET['post_type']) && 'product' === $_GET['post_type'] 
        && ! empty($wp_query) && $wp_query->post_count == 0 ) {
            wp_redirect( get_permalink( 99 ) );
            exit();
        }
    }
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.