I hope someone can help. I've set up some code (thanks to this post) that adds a product to my cart if the value of the cart is over $50.
That works. However, if the value is less than $50, I want to make sure that product is NOT in the cart. So say a user adds a product, the additional product is added, but they then remove a product so the value is under $50 (not including the new product added!) ... I want it to remove the product that was added.
I tried to implement the code as in the post mentioned above:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
// Bonus products
$product_1 = '4751';
$product_2 = '4752';
$product_3 = '24711';
// Get cart value in a clean format
$cart_total = WC()->cart->get_cart_subtotal();
$cart_total = html_entity_decode($cart_total, ENT_QUOTES, 'UTF-8');
$cart_total_format = strip_tags($cart_total);
$cart_value = preg_filter("/[^0-9]/", "", $cart_total_format);
$sum_raw = $cart_value;
// Set the sum level
$level3 = '50';
// Check sum and apply product
if ($sum_raw >= $level3) {
// Cycle through each product in the cart and check for match
$found = 'false';
foreach (WC()->cart->cart_contents as $item) {
global $product;
$product_id = $item['variation_id'];
if ($product_id == $product_3) {
$found = 'true';
}
}
// If product found we do nothing
if ($found == 'true') {}
// else we will add it
else {
//We add the product
WC()->cart->add_to_cart($product_3);
}
}
// Check if sum
if ($sum_raw < $level3) {
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
if ($cart_item['variation_id'] == $product_3) {
//remove single product
$woocommerce->cart->remove_cart_item($cart_item_key);
}
}
}
}
But it's not removing the product. :/ Anyone got any ideas why it wouldn't work, or if there's a better solution to check the cart: if cart > $50 add a product... if it ever changes and goes < $50, remove that same product...
And also exclude that newly added product from the checks (so < $50 NOT including that product that's just been added programmatically).
Please help! :(