While offering BOGO Offers you can also fine-tune the discounts using these straightforward code snippets. This custom function is useful in adding a specific product as a gift to the cart and applies a 50% discount to the auto-added product. This way you can introduce cross-sell related products and make customers explore and purchase such complementary products at a discounted price.
add_action('woocommerce_cart_calculate_fees', 'ts_add_gift_id_in_cart'); function ts_add_gift_id_in_cart() { if (is_admin()) return; if (WC()->cart->is_empty()) return; $discount = 0; $product_gifted_id = 922; // Check if gift id is in cart $product_gifted_cart_id = WC()->cart->generate_cart_id($product_gifted_id); $product_gifted_in_cart = WC()->cart->find_product_in_cart($product_gifted_cart_id); if ($product_gifted_in_cart) { $product_gifted = wc_get_product($product_gifted_id); $price = $product_gifted->get_price(); $discount -= ($price * 20) / 100; // apply 50% discount on the other product } // If gift is not in cart, add it if (!$product_gifted_in_cart) { WC()->cart->add_to_cart($product_gifted_id); } if ($discount != 0) { WC()->cart->add_fee('Discount', $discount, true); # Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false) } }
Output
When the customer adds any product to the cart, the free product is automatically added with the discount amount specified in the code.
Alternatively, you can restrict the free product to be added for certain product categories as mentioned in this post. Check out how to implement buy 1 get 2 free action in WooCommerce based on different scenarios.