0

Im trying to empty the Woocomerce cart whenever a visitor navigates to a specific page (with id #1).

Environment:

WP 5.4.2

Woocomerce 4.2.2

Woodmart theme

Litespeed cache (disabled) and applied these recommendations

Tested with google chrome/Firefox browsers. both incognito and normal mode.

none of the answers on this similar question helped

Im using this code in functions.php:

add_action( 'template_redirect', 'woocommerce_clear_cart' );
function woocommerce_clear_cart() {
  global $woocommerce, $post;
    if( $post->ID == 1) {
      WC()->cart->empty_cart();
      WC()->session->set('cart', array());
    }
}

Result:

  1. customer goes to product page and adds products to cart.(my template shows the product in the mini-cart)
  2. customer navigates to page id 1.
  3. products still appears in mini-cart/or when navigating to cart page.
  4. cart is only emptied after using CTRL+F5 to reload browser without cache. or after a few times navigating between pages.

Insights:

  • Expected result happens correctly when im logged in as admin (cart emptied when navigating to page 1)
  • when emptying customer sessions (WooCommerce/Status/Tools -> Clear customer sessions ) after user adds product (between step 1 and 2 ) navigating to page id 1 gives expected result.
  • im suspecting its a browser cache issue.
  • when printing out WC()->session when page#1 loads i can see the cart items from step 1.

Is there some WC method to clear the specific customer session from the DB programatically ?

i also tried this code, but none of these gave me expected result

add_action( 'template_redirect', 'woocommerce_clear_cart' );
function woocommerce_clear_cart() {
    if( $post->ID == 1) {
        WC()->session->set( 'cart', null );
        WC()->session->set( 'cart_totals', null );

        $cart = WC()->cart; 
        foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {

                $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        } 
    }
}
buzibuzi
  • 724
  • 3
  • 15
  • 27

1 Answers1

0

Try:

add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
  global $woocommerce;

    if ( is_front_page() && isset( $_GET['empty-cart'] ) ) { 
        WC()->cart->empty_cart(); 
    }
}

This for the front page, replace with your page of choice.

Paze
  • 183
  • 1
  • 1
  • 11