Skip to content

Instantly share code, notes, and snippets.

@moskalukigor
Created August 10, 2018 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moskalukigor/67c69129abeddc9ec22282dcd6d2aa61 to your computer and use it in GitHub Desktop.
Save moskalukigor/67c69129abeddc9ec22282dcd6d2aa61 to your computer and use it in GitHub Desktop.
remove all items from cart exclude new
<?php
add_action( 'woocommerce_add_to_cart', 'remove_cart2',10 , 6 );
function remove_cart2($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data){
global $woocommerce;
if ($woocommerce->cart->get_cart_contents_count() != 0) {
$cartQty = $woocommerce->cart->get_cart_item_quantities();
$cartItems = $woocommerce->cart->cart_contents;
// Check if desired product is in cart already
if (array_key_exists($variation_id,$cartQty)) { // $product_id when buy Simple Product || $variation_id when buy Variable Product
// Then first adjust its quantity
foreach ($cartItems as $k => $v) {
if ($cartItems[$k]['key'] == $cart_item_key) {
$woocommerce->cart->set_quantity($k, 1);
}
}
// And only after that, set other products to zero quantity
foreach ($cartItems as $k => $v) {
if ($cartItems[$k]['key'] != $cart_item_key) {
$woocommerce->cart->set_quantity($k, 0);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment