Need Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another 1 is added then it should remove the previous 1
Unfortunately there is no 'action' hook before WooCommerce adds an item to the cart. But they have a 'filter' hook before adding to cart.That is how I use it:
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );function woo_custom_add_to_cart( $cart_item_data ) { global $woocommerce; $woocommerce->cart->empty_cart(); // Do nothing with the data and return return $cart_item_data;}
Based on the accepted answer and the latest Woo version 2.5.1 I updated the function to be slightly cleaner using the code woo uses in class-wc-checkout.php to clear the cart
add_filter( 'woocommerce_add_cart_item_data', '_empty_cart' ); function _empty_cart( $cart_item_data ) { WC()->cart->empty_cart(); return $cart_item_data; }
There is a filter/hook that runs before an item is added to the cart as each product goes through validation before it is added.
So when validating a product, we can check if the item if there are already items in the cart and clears those (if the current item is able to be added) and adds an error message.
/** * When an item is added to the cart, remove other products */function so_27030769_maybe_empty_cart( $valid, $product_id, $quantity ) { if( ! empty ( WC()->cart->get_cart() ) && $valid ){ WC()->cart->empty_cart(); wc_add_notice( 'Whoa hold up. You can only have 1 item in your cart', 'error' ); } return $valid;}add_filter( 'woocommerce_add_to_cart_validation', 'so_27030769_maybe_empty_cart', 10, 3 );