Cart item not removed after set_quantity to 0 with woocommerce_cart_item_removed
-
Hello.
The case is that I have an add-on product that could not be purchased as a stand alone product. It is a simple product but with different shipping class: ‘3-5days’. With this class I’m distinguishing what type of product I’m dealing with. So when I have in the cart simple product and add-on product I want to remove both of them when I remove the simple one.
Example:
Two products in the cart
simple product: Laptop
add-on product: Speakers
Action : Remove the Laptop
Back-end: I’m hooking towoocommerce_cart_item_removed
. Then checking if there is add-on in the cart. And if there is – I’m removing it as well.But the issue is that when i set the quantity of the add-on product to 0 (and everything goes well) I still have the add-on product in my cart.
Here is my code:
/*Hook on removing item from the cart*/ add_action( 'woocommerce_cart_item_removed', 'remove_addons_wsh', 10, 2 ); function remove_addons_wsh( $cart_item_key, $cart ) { //check if current product that is removed is the add-on product if( has_term( '3-5days', 'product_shipping_class', $cart_item_key ) ) { return true; } //find number of add-on prodcts in the cart $addon_count = 0; $addon_ids = array(); foreach ($cart->cart_contents as $cart_item) { if (has_term( '3-5days', 'product_shipping_class', $cart_item['product_id'])) { $addon_count++; array_push($addon_ids, $cart_item['product_id']); } } //check if overall count of products and the addon count if ( (count($cart) -1 ) > $addon_count) { return true; } //any other case - we remove all addons foreach ($addon_ids as $id) { $res = $cart->set_quantity($id,0); error_log("res:" .$res); //this does return 1(true) return true; } }
Where might be the mistake,I tried different hook like
woocommerce_remove_cart_item
but still no good. I have tried$cart->remove_cart_item($id)
and still no result;
- The topic ‘Cart item not removed after set_quantity to 0 with woocommerce_cart_item_removed’ is closed to new replies.