In one of our post, we have already discussed how to add BOGO Buy One Get One product for a fixed quantity in WooCommerce. While some items like high-priced items might well suit for fixed quantity, there are also items such as low-priced but daily-use items that are always bought in bulk. Setting a quantity range for such low-priced items are well suited to buy in bulk quantities. This code helps customers receive a free product when they meet the specified range of quantity for product A.
add_action('template_redirect', 'ts_add_product_to_cart'); function ts_add_product_to_cart() { if (!is_admin()) { global $woocommerce; $product_a_id = 922; $free_product_id = 929; // Set the targeted quantity range for the parent product A $min_targeted_qty = 5; $max_targeted_qty = 10; // Loop through cart items foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { // Check if the current product is the parent product if ($cart_item['product_id'] == $product_a_id) { // Check if the quantity of the parent product A falls within the specified range if ($cart_item['quantity'] >= $min_targeted_qty && $cart_item['quantity'] <= $max_targeted_qty) { // Check if the free product is already in the cart $free_product_cart_id = WC()->cart->generate_cart_id($free_product_id); $free_product_in_cart = WC()->cart->find_product_in_cart($free_product_cart_id); // If the free product is not in the cart, add it if (!$free_product_in_cart) { WC()->cart->add_to_cart($free_product_id); } } else { // If the quantity condition is not met, remove the free product ts_remove_free_product($free_product_id); } } } } } function ts_remove_free_product($free_product_id) { global $woocommerce; // Check if the free product is in the cart foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) { $_product = $values['data']; if ($_product->get_id() == $free_product_id) { // Remove the free product $woocommerce->cart->remove_cart_item($cart_item_key); } } }
Output
When a customer adds Coffee Mugs(Parent Product A) to their cart and purchases in bulk quantities the code checks for the below targeted quantity range.
- minimum targeted quantity=5;
- maximum targeted quantity =10;
When product A falls within the specified quantity range of 5 to 10 items, a free gift, such as a Coffee Stir Spoon, is automatically added to their cart.
When the purchased quantity of Coffee Mugs falls below the defined quantity range (5 to 10 items), and as the quantity range threshold is not met, the free gift offer is automatically removed from the customer’s cart.
Alternatively, you can also add BOGO Buy One Get One offers based on WooCommerce cart total range.