By setting a product limit for BOGO discounts, store owners can aim to increase the average order value. This code implements a “Buy One, Get One 50% Off” promotion for specific products in the WooCommerce cart, limiting the discount to a predefined quantity per product.
add_action('woocommerce_cart_calculate_fees', 'ts_bogo_fifty_percent_off', 10, 1); function ts_bogo_fifty_percent_off($cart) { if (is_admin() && !defined('DOING_AJAX')) { return; } $target_products = array(100, 456, 470); // Replace with your product IDs $product_limit = 2; // Set your product limit here $discount = 0; foreach ($cart->get_cart() as $cart_item) { if (in_array($cart_item['product_id'], $target_products)) { $qty = min($cart_item['quantity'], $product_limit); $product_limit -= $qty; $discount -= $qty * ($cart_item['data']->get_price() * 0.5); if ($product_limit <= 0) { break; } } } if ($discount < 0) { $cart->add_fee(__('BOGO 50% Off Discount'), $discount); } }
Output
If you add ‘N’ items to your cart, you can make sure that ‘Buy One Get One’ discounts only apply to certain products, and you can set a limit on how many items get the discount. In the example below, the discount is applied to only two items, as set in the code.
Similarly, you can also add a free gift based on the selected quantity in WooCommerce.