There are methods that empty the cart if you add a new product.
function wdm_empty_cart( $cart_item_data, $product_id, $variation_id )
{
global $woocommerce;
$woocommerce->cart->empty_cart();
}
But what I want is only if you add the same product. So adding if ( $in_cart )
does the job but I also do not want to empty whole cart.
Just want to delete the same product that added previously and keep the others.
I mean overwrite.
CodePudding user response:
You can use woocommerce_add_to_cart_validation
action hooks and check against products that are already in the cart. code will go in your active theme functions.php file.
add_filter('woocommerce_add_to_cart_validation', 'remove_cart_item_before_add_to_cart', 1, 3);
function remove_cart_item_before_add_to_cart($passed, $product_id, $quantity) {
$already_in_cart = false;
foreach( WC()->cart->get_cart() as $key => $item ){
// Check if the item is already is in cart.
if( $item['product_id'] == $product_id ){
$already_in_cart = true;
$existing_product_key = $key;
break;
}
}
if( $already_in_cart ){
WC()->cart->remove_cart_item($existing_product_key);
}
return $passed;
}