Empty cart before add to cart in WooCommerce

  • Home
  • Empty cart before add to cart in WooCommerce
Empty cart before add to cart in WooCommerce

This function will reset/empty the cart and will add the last product to the cart.
This is a WooCommerce PHP function that over wright the WC cart function.

We can use this function for individual product selling websites or for a subscription website.

Sefatun

Add the following code in the function.php file of your active child theme (or theme).

// Keep only last cart item
add_action( 'woocommerce_before_calculate_totals', 'keep_only_last_cart_item', 30, 1 );
function keep_only_last_cart_item( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$cart_items = $cart->get_cart();
if( count( $cart_items ) > 1 ){
$cart_item_keys = array_keys( $cart_items );
$cart->remove_cart_item( reset($cart_item_keys) );
}
}


Tested and works with both ajax-add-to-cart and normal add-to-car

Leave a Reply

Your email address will not be published.