BOGO or Buy one get one offers, when combined with the inventory threshold helps store owners to strategically clear out excess inventory. The following code checks whether the stock quantity of products in the cart is greater than a predefined threshold. When this condition is met, the free product is added to the cart.
add_action('woocommerce_before_calculate_totals', 'ts_free_product_based_on_stock', 10, 1); function ts_free_product_based_on_stock($cart) { if (is_admin() && !defined('DOING_AJAX')) return; // Define the product ID of the free product $free_product_id = 470; // Replace with your actual free product ID $minimum_stock_quantity = 5; // Set the minimum stock quantity to offer the free product // Check if the free product is already in the cart $free_product_in_cart = false; foreach ($cart->get_cart() as $cart_item) { if ($cart_item['product_id'] == $free_product_id) { $free_product_in_cart = true; break; } } // Check if any product in the cart has a stock quantity that allows offering the free product foreach ($cart->get_cart() as $cart_item) { $product = wc_get_product($cart_item['product_id']); $stock_quantity = $product->get_stock_quantity(); if (!$free_product_in_cart && $stock_quantity >= $minimum_stock_quantity) { // Add the free product to the cart $cart->add_to_cart($free_product_id); break; // Stop checking once we add the free product } } }
Output
Let’s imagine that a customer has added an Android SmartPhone to the cart. Have a look at the stock quantity of this item present in the cart from the backend as shown in this image.
As the product’s stock quantity is greater than the predefined minimum stock quantity threshold, the free product gets added to the cart.
Let’s imagine that the stock quantity of the above product falls below 5, in such cases the free product is not added to the cart.
On the contrary, you can also add free gift based on selected quantity in WooCommerce that will dynamically change the free products offered based on the quantity range selected.