Empty Woocommerce Cart before adding new item

If you happen to only wants to allow 1 item in your cart and remove all other cart item before adding one, this article might be your saver. Apparently there are a few article that uses a hook call 'woocommerce_add_to_cart' where it 'should' remove the item before adding it. But it doesn't work for newer version of woocommerce. However, there is another hook call 'woocommerce_add_to_cart_validation'. Therefore, if you would like to remove an item before adding a new item into your cart in Woocommerce, you should do something like this.

// before addto cart, only allow 1 item in a cart
add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );

function woo_custom_add_to_cart_before( $cart_item_data ) {

    global $woocommerce;
    $woocommerce->cart->empty_cart();

    // Do nothing with the data and return
    return true;
}

This will remove everything during validation before adding the item into wWocommerce cart. Try it!

One thought on “Empty Woocommerce Cart before adding new item

Comments are closed.