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.

Empty cart before add to cart in WooCommerce

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-cart

5 Comments

  1. certainly like your website but you need to take a look at the spelling on quite a few of your posts Many of them are rife with spelling problems and I find it very troublesome to inform the reality nevertheless I will definitely come back again

  2. Hello my loved one I want to say that this post is amazing great written and include almost all significant infos I would like to look extra posts like this

  3. Your blog is a constant source of inspiration for me. Your passion for your subject matter shines through in every post, and it’s clear that you genuinely care about making a positive impact on your readers.

Leave a Reply

Your email address will not be published. Required fields are marked *