INSOMNIA INC

WooCommerce Buy 3 get 1 Free For Variations/Attributes

Woocommerce buy 3 get 1 free for variations-attributes featured image

For reddit request: Buy 2 Get 1 Free plugin for woocommerce

What does this code do?

This code snippet for WooCommerce gives customers a free item for every 4th variation of a different product in their cart. The conditions are that the attribute term (variation) must match across 4 seperate products. When they do, the cost of one product is deducted from the cart.

Let’s say you sell music tracks in different formats like MP3, WAV, and FLAC. If a customer buys 4 different songs in MP3 format, they get one of those songs for free! The discount is applied at checkout, so they’ll see the discount in their total cost. And if they buy 8 MP3 songs, they’ll get 2 songs for free!

Things to note

Before you start using this code, keep the following things in mind:

  • Attributes and Terms must be set at a global level: This means that all products that use this discount must be assigned the same attribute and terms for variations.
  • All variations must have the same price: This code assumes that all variations within a term group have the same price. MP3s can be $3 and WAV can be $5 but this must be the same across all products. This means that all MP3 variations for whatever song must always be $3 and WAV must all be $5 and so forth.

How to use

To use this code snippet, you’ll need to add it to your WordPress site. You can do this in one of two ways:

  1. Child theme functions.php: If you have a child theme set up, you can add the code to the functions.php file. Do not add to your themes functions.php as updating the theme will wipe the code.
  2. Code Snippets Plugin: If you’re not comfortable with coding or don’t have a child theme, you can use a plugin like Code Snippets to add the code. This plugin allows you to add code snippets to your site without modifying your theme files and provides a failsafe if anything goes wrong.

Jump To Code

Setting up

To make the code work, you’ll need to set the attribute and terms to match your products. Look for the following lines of code:

$attribute_name = 'Colour';
$terms = array('Blue', 'Black', 'White');

Change ‘Colour’ to the attribute you use, like ‘Size’ or ‘Material’. Update the terms to match your product variations, like ‘Small’, ‘Medium’, ‘Large’.

Adjust the Number of Items for a Freebie

You can change how many items a customer needs to buy to get one free. Look for this part:

if ( $term_count >= 4 ) { // Change this number to adjust the threshold (e.g. 3, 5, etc.)
    $discount_count = floor( $term_count / 4 ); // Change this number to adjust the discount ratio (e.g. 3, 5, etc.)

Change 4 to the number you want. For example, if you want “Buy 5, Get 1 Free,” change 4 to 5.

Code Breakdown

Let’s break down how the code works:

Hook to Calculate Fees

add_action( 'woocommerce_cart_calculate_fees', 'insomniainc_variation_party_discount' );

This line tells WooCommerce to use our function to calculate fees in the cart.

Function to Apply Discounts

function insomniainc_variation_party_discount( $cart ) {

This is the main function that does the work.

Define Attributes and Terms

$attribute_name = 'Colour';
$terms = array('Blue', 'Black', 'White');

These lines define the attribute (like colour) and the terms (like blue, black, and white) we are checking.

Loop Through Each Term

foreach ( $terms as $term ) {
     $term_count = 0;
        $term_product = null;
        $discount_count = 0;
        
        // Loop through each item in the cart
        foreach ( $cart->get_cart() as $cart_item ) {
            $product = $cart_item['data'];
            $product_name = $product->get_name();
            
            // Check if the product name contains the term
            if ( strpos( $product_name, $term )!== false ) {
                $term_count++;
                $term_product = $product; // store the product for later use
            }
}

This loop goes through each term (like blue, black, and white).

Count Products and Apply a Discount

foreach ( $cart->get_cart() as $cart_item ) {            $product = $cart_item['data'];
            $product_name = $product->get_name();
            
            // Check if the product name contains the term
            if ( strpos( $product_name, $term )!== false ) {
                $term_count++;
                $term_product = $product; // store the product for later use
            }
}

This loop goes through each item in the cart and counts how many times each term appears.

if ( $term_count >= 4 ) {
    $discount_count = floor( $term_count / 4 );
    $product_price = $term_product->get_price();
    $discount_text = $discount_count. ' Free '. $term;
    $cart->add_fee( $discount_text, -$product_price * $discount_count );
}

If there are enough items (4 in this case), it calculates how many free items are to be given and applies the discount.

Support the support: If you’d be inclined to support my efforts, you can caffeinate me. This helps me actively assist others like yourself within the Reddit WordPress, WooCommerce, and Divi communities by providing unique solutions to non-standard requests and free alternatives to expensive subscription plugins.

HOW TO USE

To use the code snippet below, you’ll need to add it to your WordPress site. You can do this in one of two ways:

  1. Child theme functions.php: If you have a child theme set up, you can add the code to the functions.php file. Do not add to your themes functions.php as updating the theme will wipe the code.
  2. Code Snippets Plugin: If you’re not comfortable with coding or don’t have a child theme, you can use a plugin like Code Snippets to add the code. This plugin allows you to add code snippets to your site without modifying your theme files and provides a failsafe if anything goes wrong.