Created
August 10, 2018 07:28
-
-
Save moskalukigor/67c69129abeddc9ec22282dcd6d2aa61 to your computer and use it in GitHub Desktop.
remove all items from cart exclude new
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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