This PHP code enables you to target specific products to promote for discounts offering buy a set quantity of a specific product and get a set number for free. In this example, we use buy 10 get 2 free however you can simply change the numbers to anything you like.
Here’s an example of the output on the cart page :
![](https://wpsites.net/wp-content/uploads/2024/07/10.png)
![](https://wpsites.net/wp-content/uploads/2024/07/20.png)
Here’s the code for your child themes functions.php file
add_action('woocommerce_cart_calculate_fees', 'buy_ten_get_two_free', 10, 1 );
function buy_ten_get_two_free( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Set HERE your targeted variable products IDs
$targeted_product_ids = array( 185 );
$each_n_items = 10; // Number of items required to get a two free
$free_items_count = 2; // Number of free items to give
$discount = 0; // Initializing
$count_items = 0; // Initializing counter for eligible items
foreach ( $cart->get_cart() as $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$qty = intval( $cart_item['quantity'] );
$count_items += $qty;
}
}
// Calculate number of free items
$free_items = floor( $count_items / $each_n_items ) * $free_items_count;
// Calculate total price of items eligible for discount
foreach ( $cart->get_cart() as $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$qty = intval( $cart_item['quantity'] );
$price = floatval( $cart_item['data']->get_price() );
// Calculate how many items are eligible for discount
$eligible_qty = min( $qty, $free_items );
// Calculate the discount based on eligible quantity
$discount += $eligible_qty * $price;
// Deduct the eligible items from free_items count
$free_items -= $eligible_qty;
}
}
if ( $discount > 0 ) {
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("Buy 10 Get 2 Free"), 'notice');
// Apply the discount
$cart->add_fee( __("Buy 10 Get 2 Free"), -$discount, true );
}
}
Code Settings
You’ll need to make a few small adjustments to the code above.
- Swap out the 185 with the product ID you want to target
- Swap out the 10 to match the number of items your customer needs to buy to get 2 free
- Swap out the 2 to match the number of items your customers get for free for very 10 they pay for
Note : Your customers will get 2 free for every 10 they purchase so if they purchase 100, they will get 20 for free.
The code is limited in that it it only targets 1 specific product however you can add comma separated products ids to target more than 1 product.
Need an extended version of this code? Try the free products based on quantity plugin for WooCommerce.
Not exactly what you’re looking for?
Was This Tutorial Helpful?