I want to add a certain free gift, depending on cart amount in WooCommerce.
Let's say:
- Less than 1500 - no free gift
- Between or equal to 1500 - 1999 - add a free product (1)
- Greater than or equal to 2000 - add another free product (2), remove free product (1)
Based on Add free gifted product for a minimal cart amount in WooCommerce answer code, which works if i add 1 element, but if i add more it stop working.
This is my code attempt:
// Add free gifted product for specific cart subtotal
add_action('woocommerce_before_calculate_totals', 'check_free_gifted_product');
function check_free_gifted_product($cart)
{
if (is_admin() && !defined('DOING_AJAX'))
return;
// Settings
$free_product_id = 158;
$targeted_subtotal = 1500;
$targeted_subtotal_max = 2000;
$cart_subtotal = 0; // Initializing
// Loop through cart items (first loop)
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
// When free product is is cart
if ($free_product_id == $cart_item['product_id']) {
$free_key = $cart_item_key;
$free_qty = $cart_item['quantity'];
$cart_item['data']->set_price(0); // Optionally set the price to zero
} else {
$cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
}
}
// If subtotal match and free product is not already in cart, add it
if (!isset($free_key) && $cart_subtotal >= $targeted_subtotal && $cart_subtotal <= $targeted_subtotal_max) {
$cart->add_to_cart($free_product_id);
}
// If subtotal doesn't match and free product is already in cart, remove it
elseif (isset($free_key) && $cart_subtotal < $targeted_subtotal || $cart_subtotal > $targeted_subtotal_max) {
$cart->remove_cart_item($free_key);
}
// Keep free product quantity to 1.
elseif (isset($free_qty) && $free_qty > 1) {
$cart->set_quantity($free_key, 1);
}
}
Any adivce?