Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins

How to Add BOGO (Buy One Get One) offer based on Product Stock Count in WooCommerce?

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'))

    // 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;

    // 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
            break; // Stop checking once we add the free product


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.

Buy One Get One offer based on Product Stock Count in WooCommerce

As the product’s stock quantity is greater than the predefined minimum stock quantity threshold, the free product gets added to the cart.

Adding BOGO offer based on Product Stock Count in WooCommerce

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.

Buy One Get One offer based on Product Stock Count in WooCommerce
Buy One Get One offer based on Product Stock Count in WooCommerce

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.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x