The code in this download folder enables you to give away a free product for every 2 purchased using WooCommerce.
Demo Video
Shows how to offer a free product for every 2 purchased using WooCommerce.
How The Code Works
Certainly! Let’s break down how the provided code works:
1. Hooking into woocommerce_cart_calculate_fees
:
– The line add_action('woocommerce_cart_calculate_fees', 'buy_two_get_one_free', 10, 1 );
hooks the buy_two_get_one_free
function into the cart fee calculation process.
2. Function buy_two_get_one_free
:
– Cart Loop : It starts by looping through each item in the cart using $cart->get_cart()
.
– Targeted Products : It checks if the product in the cart is one of the targeted variable products specified in $targeted_product_ids
(in this case, product ID 35).
– Collecting Prices : For each quantity of the targeted product, it collects the price of the product in the $items_prices
array.
3. Calculate Discount :
– After collecting the prices, the code calculates the discount based on the “Buy 2 Get 1 Free” logic.
– It iterates through the collected prices and accumulates the discount for every third item (since it’s a “Buy 2 Get 1 Free” offer).
4. Apply Discount :
– If the total discount ($discount
) is greater than 0, it displays a notice to the user (optional) and then applies the discount as a fee using $cart->add_fee( __("Buy 2 Get 1 Free"), -$discount, true );
.
– The fee is applied as a negative amount, effectively reducing the total cart price.
5. Display Notice :
– The wc_add_notice
function is used to display a notice to the user. This is optional and can be adjusted or removed based on your preference.
6. Note :
– The last argument in add_fee
(true
) determines whether the fee should be taxable or not. You can adjust it based on your tax requirements.
This code is written to implement a “Buy 2 Get 1 Free” discount for specific variable products (with product ID 35 in this case). It calculates the discount based on the number of items in the cart and applies the discount as a fee.
Code Installation
- Copy and paste the PHP code to the end of your child themes functions file or custom functionality/code snippets plugin.
- Swap out the product id on line 9 or add a comma separated list of product ids.
Leave a Reply