How to avoid infinite loop when using woocommerce_remove_cart_item

We’re running a promotion where a customer needs to buy 2 products together to receive a discount. I need to ensure if they remove one of the 2 products, the other product is removed as well.

add_action(‘woocommerce_remove_cart_item’, ‘check_and_remove_cart_item’, 10, 2);

function check_and_remove_cart_item($cart_item_key, $cart) {
// Get the removed cart item
$removed_item = $cart->cart_contents[$cart_item_key];

$PRODUCT_ID_1 = 45585;
$PRODUCT_ID_2 = 30744;

if ($removed_item[‘product_id’] == $PRODUCT_ID_1) {
foreach ($cart->get_cart() as $key => $cart_item) {
if ($cart_item[‘product_id’] == $PRODUCT_ID_2) {
$cart->remove_cart_item($key);
break; // Stop the loop after removing the item
}
}
} elseif ($removed_item[‘product_id’] == $PRODUCT_ID_2) {
foreach ($cart->get_cart() as $key => $cart_item) {
if ($cart_item[‘product_id’] == $PRODUCT_ID_1) {
$cart->remove_cart_item($key);
break;
}
}
}
}

This should work, however what happens is it seems to cause an infinite loop. Removing item #1 calls remove\_cart\_item on item #2, which then loops back and calls remove\_cart\_item on #1, and so on.

Is there a way to fire this, AFTER the item is removed, as to avoid it continually looping around? From googling it appears there is a “woocommerce\_cart\_item\_removed” hook, but I cannot find a lot of great examples using it for this kind of purpose?

​

1 Comment
  1. Call `remove_action(‘woocommerce_remove_cart_item’, ‘check_and_remove_cart_item’, 10, 2);` inside your action. Then enable the add_action again at the end of the function.

    Your function can also be written more efficiently eg

    IF ($removed_product == $p1 OR $removed_product == $p2) {}

    No need to have the same code twice.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer