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

How to Apply a Recursive BOGO Rule for the Same Product in WooCommerce?

This approach encourages customers to increase their order quantities to maximize the benefits of the “Buy One Get One” promotions. For eg. if 2 items are bought, 1 item of the same product is given the discount. If 4 items are bought 2 is given free and so on the offer continues. If the customer adds more items with an even quantity, the code goes through the same process in a recursive manner.

add_action('woocommerce_cart_calculate_fees', 'ts_custom_discount', 10, 1);

function ts_custom_discount($cart)
    if (is_admin() && !defined('DOING_AJAX')) return;

    $targeted_product_id = 54; // Set HERE your targeted product ID

    // Initializing variables
    $discount = $qty_notice = 0;
    $parent_prices = array();

    // Loop through cart items
    foreach ($cart->get_cart() as $key => $cart_item) {
        if (in_array($targeted_product_id, [$cart_item['product_id'], $cart_item['variation_id']])) {
            $quantity = (int) $cart_item['quantity'];
            $qty_notice += $quantity;

            // Collect the price of the parent product
            $parent_prices[] = floatval($cart_item['data']->get_price());

    // Check if the quantity is a multiple of 2 (even)
    if ($qty_notice % 2 == 0) {
        // Calculate the number of free items
        $free_items = $qty_notice / 2;

        // Apply discount based on the number of free items
        $discount -= $free_items * floatval($parent_prices[0]);

    // Applying the discount
    if ($discount != 0) {
        $cart->add_fee('Custom Discount', $discount, true);

        // Displaying a custom notice (optional)
        wc_clear_notices(); // clear other notices on the checkout page.
        if (!is_checkout()) {
            wc_add_notice(__("Buy One get One discount Applied."), 'notice');
    // Display a custom notice on the cart page when quantity is not enough
    elseif ($qty_notice > 0 && $qty_notice % 2 != 0) {
        wc_clear_notices(); // clear other notices on the checkout page.
        if (is_cart()) {
            wc_add_notice(__("Add more items to get the BOGO Offer."), 'notice');


When the customer adds products to the cart, the code loops through each item in the cart to identify the targeted product and adds a free product for every even quantity. If the customer adds 6 items, the code calculates 6/2=3 free items and applies a full discount for 3 items of the product.

Similarly, you can also automatically add free product for more number of categories. Check out this guide that will help you to automatically add a product to your WooCommerce cart based on ‘N’ number of conditions.

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