Determine whether on shop page in woocommerce

4.8k views Asked by At

My client wants the checkout to be "streamlined" to skip the cart page and go straight to checkout one product at a time. I got that covered but I also need to automatically empty the cart if the customer decides not to confirm checkout.

For this I wanted to check whether or not I'm on any other page than cart or checkout and do it there but all the commands I tried (is_shop(), is_front_page(), is_page('Shop'), is_product(), is_home()) always return false so I'm not sure what to do about it. This is how I'm trying to do it (in my themses functions.php):

function reset_cart_front() {
  global $woocommerce;
    echo "Attempting to empty<br>";

    if (is_shop()) { 
        echo "is right page<br>"; 
        $woocommerce->cart->empty_cart(); 
    } else {
        echo "is not right<br>";
    }

}
add_action( 'init', 'reset_cart_front' );

what gives?

2

There are 2 answers

0
user81993 On

Nevermind, I figure it out!

function reset_cart_shop_loop() {
    global $woocommerce;
    $woocommerce->cart->empty_cart();
}
add_action( 'woocommerce_before_shop_loop', 'reset_cart_shop_loop' );
0
rnevius On

Correct me if I'm wrong...but I think you should check if the current page is_checkout(), and empty the cart if it's not:

function reset_cart_front() {
    global $woocommerce;

    if ( !is_checkout() ) { 
        $woocommerce->cart->empty_cart(); 
    }

}
add_action( 'template_redirect', 'reset_cart_front' );

I also think 'init' is too early to hook (and would recommend trying 'template_redirect').