Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios?

We all love surprises. Isn’t it? 🙂 Surprise can be anything like a birthday surprise or maybe receiving a gift unexpectedly. You as a Store owner, running a store on the WooCommerce platform, have you ever thought to surprise your customers with some discounted or FREE stuff? Hell yeah!

In this post, we will see how simple it is to automatically add a product to your WooCommerce cart as per the different scenarios listed below:

1. Add to Cart action: When Product A is added to the cart, then also add Product B (Free Product) to the cart.

2. Condition: When the cart total reaches a certain amount, add the free product to the cart.
3. Website Visit: Adding free product to the cart when a customer visits your website.

4. Automatically add free product for more categories.

5. Auto Add Free Product based on Cart Total, Excluding Specific Items.

6. Auto Add Free Product based on Cart Total, Excluding Specific Product Tags.

7. Auto-Add and Remove Free Product Based on Cart Total, Excluding Specific Product Tags in WooCommerce

This post will be knowledgeable to store owners as well as developers. The store owner can simply place the code snippets in functions.php and the developer can see the logic for automatically adding the product to cart.

1. Add to Cart action: When Product A is added to cart, then also add Product B (Free Product) to the cart

Suppose you are selling Sports & Fitness Equipments on your store and you want to gift Bat Grip when the customer adds the Cricket Bat in their basket. Let’s see how we can achieve this.

First, we will create the product called MRF Cricket Bat and we will add it to sports product category. The Bat Grip will be the free product in your store.

The customer is on the MRF Cricket Bat product page and adding it to the cart so the Bat Grip should automatically get added to the cart.

Automatically adding product to cart on Add to Cart button click
Automatically adding product to cart on Add to Cart button click

To achieve this, WooCommerce provides woocommerce_add_to_cart action hook which will execute on Add to Cart button click. Using the same we can create our custom code as shown below.

function aaptc_add_product_to_cart( $item_key, $product_id ) {

    $product_category_id 	= 123; // sports category id

    $product_cats_ids 	= wc_get_product_term_ids( $product_id, 'product_cat' );

    if ( ! is_admin() && in_array( $product_category_id, $product_cats_ids ) ) {
        $free_product_id = 12989;  // Product Id of the free product which will get added to cart
        $found 		= false;

        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $free_product_id )
                    $found = true;
                
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $free_product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $free_product_id );
        }        
    }    
}

add_action( 'woocommerce_add_to_cart', 'aaptc_add_product_to_cart', 10, 2 );

As you can see in the above code snippet, we have used the woocommerce_add_to_cart action hook and it will execute the code inside the aaptc_add_product_to_cart() callback function. We will get the product ID from function arguments and based on the product ID we are fetching the categories. You can get the IDs of the categories for the product using wc_get_product_term_ids().

Next, we are checking if the product that is being added to the cart is coming under the sports category and if the Bat Grip product is not present in the cart then the code will add it.

2. Condition: When the cart total reaches a certain amount add the free Product to the cart

Suppose you are selling Electronic items in your store and you want to gift cleaning kit if the cart total is more than the particular amount.

To achieve this, we can use the same code snippet used for automatically adding the product to the basket when the customer visits the website.

Just the difference will be that we will use template_redirect action hook instead of init hook to add some more conditions in the code snippet.

The init hook is executing before the Cart Calculations performed by WooCommerce so no cart information will be available. Hence we are using the template_redirect hook to get the cart total.

As you can see in the below code snippet, I have used $woocommerce->cart->total to get the cart total. And compared it with the total amount required to automatically adding Cleaning Kit to the cart.

function aapc_add_product_to_cart() {
    global $woocommerce;
    
    $cart_total	= 500;	

    if ( $woocommerce->cart->total >= $cart_total ) {
        if ( ! is_admin() ) {
            $free_product_id = 12989;  // Product Id of the free product which will get added to cart
            $found 		= false;

            //check if product already in cart
            if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
                foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                    $_product = $values['data'];
                    if ( $_product->get_id() == $free_product_id )
                    	$found = true;	                
                }
                // if product not found, add it
                if ( ! $found )
                    WC()->cart->add_to_cart( $free_product_id );
            } else {
                // if no products in cart, add it
                WC()->cart->add_to_cart( $free_product_id );
            }        
        }
    }        
}

add_action( 'template_redirect', 'aapc_add_product_to_cart' );
Automatically adding product to cart when cart total more than $500
Automatically adding product to cart when cart total more than $500

3. Website visit: Adding free product product to the cart when a customer visits your website

Let’s say you are selling Sports & Fitness Equipments on your store and you want that when a customer
 
is visiting your website then a Cap should automatically get added to their basket as a gift.
 
Automatically adding product to cart on website visit
Automatically adding product to cart on website visit

WordPress has init hook using which we can implement our custom code snippet and place it in functions.php file to automatically add the product to your WooCommerce cart on website visit. Below is the code snippet to achieve the same.

function aaptc_add_product_to_cart() {

    if ( ! is_admin() ) {
        $product_id = 12986;  // Product Id of the free product which will get added to cart
        $found 	= false;

        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }    
}

add_action( 'init', 'aaptc_add_product_to_cart' );

Let’s understand what I have done in the above code snippet. As you can in the above code snippet we used init WordPress hook and it will call the aaptc_add_product_to_cart() function. In this function, we are fetching the cart items using $woocommerce->cart->get_cart() and checking if the free product is present in the cart or not. If not then add it to the cart using WC()->cart->add_to_cart() function else don’t do anything.

We can also use template_redirect action hook.

4. Automatically add a free product for more categories

Let’s consider that you have many categories of products in your store. The below code snippet helps you to add free products only when the customer chooses products from specific categories. For example, if a customer selects items from both these “Electronics” and “Clothing” categories that have been explicitly mentioned in the code,  and so they receive a free product as a special offer.

function ts_aaptc_add_product_to_cart( $item_key, $product_id ) {

    $product_category_ids = array( 57, 58 ); // Add more category IDs here

    $product_cats_ids = wc_get_product_term_ids( $product_id, 'product_cat' );

    if ( ! is_admin() ) {

        foreach ( $product_category_ids as $category_id ) {

            if ( in_array( $category_id, $product_cats_ids ) ) {

                $free_product_id = 1494; // Product Id of the free product which will get added to cart

                $found = false;

                // Check if product is already in cart

                if ( sizeof( WC()->cart->get_cart() ) > 0 ) {

                    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {

                        $_product = $values['data'];

                        if ( $_product->get_id() == $free_product_id )

                            $found = true;

                    }

                    // If product not found, add it

                    if ( ! $found )

                        WC()->cart->add_to_cart( $free_product_id );

                } else {

                    // If no products in cart, add it

                    WC()->cart->add_to_cart( $free_product_id );

                }

            }

        }

    }

}

add_action( 'woocommerce_add_to_cart', 'ts_aaptc_add_product_to_cart', 10, 2 );

Output

The image shows us that if either the product is chosen from electronics category or sports category, then the free product is added to cart.

4. Automatically add a free product for more categories
4. Automatically add a free product for more categories

Let’s understand how the code works: The function named ts_aaptc_add_product_to_cart is hooked to the woocommerce_add_to_cart action. When an item is added to the WooCommerce cart, this function is executed.

Inside the function, it checks if the added product belongs to specific product categories, identified by their category IDs (e.g., 57 and 58). It uses wc_get_product_term_ids to obtain the product’s category IDs and compares them with the predefined category IDs.

If the added product falls within the specified categories and isn’t already present in the cart, the code adds a free product to the cart. The free product is identified by its product ID, which is set to 1494. It first checks if the free product is already in the cart by iterating through existing cart items. If not found, the code adds the free product to the cart using the WC()->cart->add_to_cart() method.

5. Auto Add Free Product based on Cart Total, Excluding Specific Items

Imagine an online store offering a free gift when your cart total reaches a certain amount. To avoid giving away free gifts with expensive items, the code provided below will exclude certain items from being added to the cart total. This way, you’ll only receive the free gift when you meet the condition with eligible products in your cart.

function ts_add_free_product_to_cart() {
    global $woocommerce;


    // Define the cart total threshold for the free product
    $cart_total_threshold = 100;


    // Define an array of product IDs that should be excluded from counting towards the cart total
    $excluded_product_ids = array(1589, 1575); // Add the IDs of the products to be excluded


    // Calculate the cart total for eligible products only
    $eligible_cart_total = 0;


    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
        $_product = $values['data'];
        $product_id = $_product->get_id();


        // Check if the product is in the excluded list
        if (!in_array($product_id, $excluded_product_ids)) {
            $eligible_cart_total += $values['line_total'];
        }
    }


    // Check if the eligible cart total meets the threshold
    if ($eligible_cart_total >= $cart_total_threshold) {
        if (!is_admin()) {
            $free_product_id = 1494; // Product Id of the free product


            // Check if the free product is not already in the cart
            $found = false;
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
                $_product = $values['data'];
                if ($_product->get_id() == $free_product_id) {
                    $found = true;
                    break;
                }
            }


            // If the free product is not found, add it to the cart
            if (!$found) {
                WC()->cart->add_to_cart($free_product_id);
            }
        }
    }
}


add_action('template_redirect', 'ts_add_free_product_to_cart');

Output

In the below output, even though the cart total condition to be $100 is met, the free gift has not been

 added. It is because these IDs are specified in the code to get excluded from adding it to the cart total.

Use case: Cart total is met with excluded products, no free product is added.

5. Auto Add Free Product based on Cart Total, Excluding Specific Items
5. Auto Add Free Product based on Cart Total, Excluding Specific Items

This code creates a function, add_free_product_to_cart, which is hooked to the template_redirect action. The functions create specific criteria for automatically adding a free product to the cart when the cart’s total value reaches or exceeds a predefined threshold, which is set as $cart_total_threshold. The code also allows for the exclusion of certain products from influencing the cart total by maintaining an array of their product IDs, found in $excluded_product_ids.

The code then calculates the eligible cart total by iterating through the cart’s items and excluding those identified in the excluded_product_ids array. If the eligible cart total meets the specified threshold, and if the free product is not already in the cart, the code adds the free product to the cart.

6. Auto Add Free Product based on Cart Total, Excluding Specific Product Tags

Similar to the above condition that excludes specific product items based on product IDs, the code given below will check for excluded product tag terms and calculate the eligible cart total accordingly.

function ts_add_free_product_to_cart() {
    global $woocommerce;

    // Define the cart total threshold for the free product
    $cart_total_threshold = 100;

    // Define an array of product tag terms to be excluded
    $excluded_product_tags = array('costly-products', 'budget-buys'); // Add the products tags to be excluded

    // Calculate the cart total for eligible products only
    $eligible_cart_total = 0;

    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
        $_product = $values['data'];
        $product_id = $_product->get_id();

        // Check if the product has any excluded tag terms
        $product_tags = get_the_terms($product_id, 'product_tag');
        $excluded_product = false;

        if ($product_tags) {
            foreach ($product_tags as $tag) {
                if (in_array($tag->slug, $excluded_product_tags)) {
                    $excluded_product = true;
                    break;
                }
            }
        }

        // Check if the product is not in the excluded list
        if (!$excluded_product) {
            $eligible_cart_total += $values['line_total'];
        }
    }

    // Check if the eligible cart total meets the threshold
    if ($eligible_cart_total >= $cart_total_threshold) {
        if (!is_admin()) {
            $free_product_id = 470; // Product Id of the free product

            // Check if the free product is not already in the cart
            $found = false;
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
                $_product = $values['data'];
                if ($_product->get_id() == $free_product_id) {
                    $found = true;
                    break;
                }
            }

            // If the free product is not found, add it to the cart
            if (!$found) {
                WC()->cart->add_to_cart($free_product_id);
            }
        }
    }
}

add_action('template_redirect', 'ts_add_free_product_to_cart');

For example, let’s create product tags such as ‘Budget buys’ and ‘costly products’ and assign it to some products.

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

The products that have been assigned to these tags are shown below:

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

Output

The free gift gets added when the cart total reaches the threshold amount of $100, excluding the items of product tag terms that are specified in the code.

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

Even if the cart total has reached the threshold amount of $100, if any of the products in the cart have the specified product tags mentioned in the code,  then the free gift will not be added.

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

7. Auto-Add and Remove Free Product Based on Cart Total, Excluding Specific Product Tags in WooCommerce

In the above scenario, we have discussed how to add free products based on cart total, excluding certain product tags. Once the threshold is met, the free product is added. If the customer, at any point, removes the parent product (from cart) that were eligible to meet the threshold, the following code helps to remove the free product from the cart. 

/**
 * Adding the free product to the cart based on cart total, excluding specific product tags.
 */
function ts_add_free_product_to_cart() {
    global $woocommerce;

    // Define the cart total threshold for the free product
    $cart_total_threshold = 100;

    // Define an array of product tag terms to be excluded
    $excluded_product_tags = array('costly-products', 'budget-buys'); // Add the products tags to be excluded

    // Calculate the cart total for eligible products only
    $eligible_cart_total = 0;

    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
        $_product = $values['data'];
        $product_id = $_product->get_id();

        // Check if the product has any excluded tag terms
        $product_tags = get_the_terms($product_id, 'product_tag');
        $excluded_product = false;

        if ($product_tags) {
            foreach ($product_tags as $tag) {
                if (in_array($tag->slug, $excluded_product_tags)) {
                    $excluded_product = true;
                    break;
                }
            }
        }

        // Check if the product is not in the excluded list
        if (!$excluded_product) {
            $eligible_cart_total += $values['line_total'];
        }
    }

    // Check if the eligible cart total meets the threshold
    if ($eligible_cart_total >= $cart_total_threshold) {
        if (!is_admin()) {
            $free_product_id = 470; // Product Id of the free product

            // Check if the free product is not already in the cart
            $found = false;
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
                $_product = $values['data'];
                if ($_product->get_id() == $free_product_id) {
                    $found = true;
                    break;
                }
            }

            // If the free product is not found, add it to the cart
            if (!$found) {
                WC()->cart->add_to_cart($free_product_id);
            }
        }
    }
}

/**
 * Removing the free product from the cart under specific conditions.
 */
function ts_remove_free_product_from_cart() {
    if (is_cart() || is_checkout()) {
        global $woocommerce;

        // Define the cart total threshold for the free product
        $cart_total_threshold = 100;

        // Define an array of product tag terms to be excluded
        $excluded_product_tags = array('costly-products', 'budget-buys'); // Add the products tags to be excluded

        $free_product_id = 470; // Product Id of the free product
        $eligible_cart_total = 0;

        foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
            $_product = $values['data'];
            $product_id = $_product->get_id();

            // Check if the product has any excluded tag terms
            $product_tags = get_the_terms($product_id, 'product_tag');
            $excluded_product = false;

            if ($product_tags) {
                foreach ($product_tags as $tag) {
                    if (in_array($tag->slug, $excluded_product_tags)) {
                        $excluded_product = true;
                        break;
                    }
                }
            }

            // Check if the product is not in the excluded list
            if (!$excluded_product) {
                $eligible_cart_total += $values['line_total'];
            }
        }

        // Check if any excluded products are removed from the cart
        $excluded_products_removed = false;
        foreach ($woocommerce->cart->removed_cart_contents as $removed_item) {
            $removed_product_id = $removed_item['product_id'];

            if (in_array($removed_product_id, $excluded_product_tags)) {
                $excluded_products_removed = true;
                break;
            }
        }

        // Check if any other products are removed from the cart
        $other_products_removed = !empty($woocommerce->cart->removed_cart_contents) && !$excluded_products_removed;

        // If other products are removed and the eligible cart total is below the threshold, remove the free product
        if ($other_products_removed && $eligible_cart_total < $cart_total_threshold) {
            // Check if the free product is currently in the cart, and remove it
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
                $_product = $values['data'];
                if ($_product->get_id() == $free_product_id) {
                    WC()->cart->remove_cart_item($cart_item_key);

                    // Log that the free product is removed from the cart
                    error_log('Free Product Removed from Cart');
                    break;
                }
            }
        }
    }
}
add_action('template_redirect', 'ts_remove_free_product_from_cart');

// Add the original function
add_action('template_redirect', 'ts_add_free_product_to_cart');

Output

The provided output demonstrates that when products added to the cart meet the specified threshold, considering the exclusion of items with specific product tags, the free product is automatically added to the cart. 

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

In the displayed image, let’s assume that the customer is removing the parent product, which initially contributed to meeting the threshold value.

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

Consequently, the absence of the parent product in the cart triggers a mechanism in the code. As a result, the free product is also removed from the cart.

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

Supplementary Features Added to the Above Scenarios

1. Remove the Free product if the Parent product is removed

So far, we’ve discussed how a free product is automatically added to the cart when the main product is added. However, there are cases when customers later remove the main product and proceed to buy only the free product with delivery charges. This could result in a loss for the store owner.
To prevent this situation, the following code snippet is designed to remove the free product if the customer decides to remove the main (parent) product from the cart. This ensures that the free item is associated with the main product and remains in the cart only when the main product is present.

Recommended Reading: How to Remove a Product from WooCommerce Cart Programatically
/**
 * Removing free product from cart when cart doesn't contain a product of a particular category.
 */
function aaptc_add_product_to_cart( $item_key, $product_id ) {
    $product_category_id = 58; // sports category id

    $product_cats_ids = wc_get_product_term_ids( $product_id, 'product_cat' );

    if ( ! is_admin() && in_array( $product_category_id, $product_cats_ids ) ) {
        $free_product_id = 1494; // Product Id of the free product which will get added to cart
        $found = false;

        // check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $free_product_id ) {
                    $found = true;
                }
            }

            // if product not found, add it
            if ( ! $found ) {
                WC()->cart->add_to_cart( $free_product_id );
            }
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $free_product_id );
        }
    }
}
add_action( 'woocommerce_add_to_cart', 'aaptc_add_product_to_cart', 10, 2 );

function ts_remove_product_from_cart() {
    // Run only in the Cart or Checkout Page
    if ( is_cart() || is_checkout() ) {
        $product_category_id = 58; // ID of category
        $prod_to_remove = 1494; // Product ID of Free Product
        $cart_contains_category = false; // Default set to false : This means cart doesn't contain any product of a particular category
        $free_pro_cart_id = "";

        foreach ( WC()->cart->cart_contents as $prod_in_cart ) {
            // Get the Variation or Product ID
            $prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id'];
            $product_cats_ids = wc_get_product_term_ids( $prod_id, 'product_cat' );

            if ( in_array( $product_category_id, $product_cats_ids ) ) {
                $cart_contains_category = true; // cart has the product of a particular category.
                break;
            }
        }

        if ( ! $cart_contains_category ) { // remove free product if the cart doesn't contain a product of a particular category
            $free_pro_cart_id = WC()->cart->generate_cart_id( $prod_to_remove );
            // Remove it from the cart by un-setting it
            unset( WC()->cart->cart_contents[ $free_pro_cart_id ] );
        }
    }
}
add_action( 'template_redirect', 'ts_remove_product_from_cart' );

      

Output

The output below depicts that when the parent product is removed, automatically the free product also gets removed from the cart.

The code hooks the woocommerce_add_to_cart event to execute the aaptc_add_product_to_cart function when products are added to the cart.

The remove_product_from_cart function checks if the cart contains specific product categories. If not, it removes the free product (ID 1494) from the cart.

Hook for Execution: The template_redirect hook ensures that the removal function runs when users navigate to different pages, maintaining cart consistency.

2. Show the free product’s original cost with a strikeout and replace the price as $0

To implement the below functionality, you must add the code snippets from the headings “Add to Cart action:”  and “Modify the Free Product’s original price to zero” followed by the provided code snippets. These steps are required since we have been involved in a three-step process here: Firstly, adding a free product to the cart, changing the free product’s original price to zero, and then displaying the product’s original price with a strikeout.

Recommended Reading: How to Add Hyperlink to Shipping Method Label @ Cart & Checkout in WooCommerce?
// Function to modify cart item price to include original price with strikethrough
function ts_modify_cart_item_price( $price, $cart_item, $cart_item_key ) {
    $free_product_id = 1494; // Product ID of the free product
    $original_price = 20; // Original price of the product


    if ( $cart_item['product_id'] == $free_product_id ) {
        // Modify the item price to include the original price with strikethrough
        $price = sprintf(
            '<del>%s</del> %s',
            wc_price( $original_price ), // Format the original price
            $price // Keep the current price
        );
    }


    return $price;
}
add_filter( 'woocommerce_cart_item_price', 'ts_modify_cart_item_price', 10, 3 );

Output

The output shown below represents that the product’s regular price is crossed out, and it displays the modified price as $0.

How to Automatically Add Free Product to WooCommerce Cart in 6 Different Scenarios? - Tyche Softwares

This code defines a function, modify_cart_item_price, which hooks to the woocommerce_cart_item_price filter. It checks if the cart item’s product ID matches the $free_product_id and, if so, modifies the item’s displayed price. The modification includes displaying the original price with a strikethrough using the <del> HTML tag and then appending the current price. This filter ensures that the original price is visually represented alongside the current price for the specified free product in the WooCommerce cart.

3. Modify the Free Product’s original price to zero

Suppose your free product’s Regular Price is $25 and if that product is automatically added to your cart, when the cart total is reached to a particular amount then you want to modify that freely added product’s price to $0. For that, you can use the below code snippet to modify the free product’s price in the cart.

function ts_add_custom_price($cart_object) {
    $cart_total = 25; // If cart total is more than this value.
    $free_product_id = 1494; // Set the price to 0 of this free product.
    $carttotal = 0;

    foreach ($cart_object->cart_contents as $key => $value) {
        $_product = $value['data'];

        if ($_product->get_id() == $free_product_id) {
            continue;
        }

        $carttotal += $value['line_total'];
    }

    if ($carttotal >= $cart_total) {
        $custom_price = 0; // This will be your custom price.

        foreach ($cart_object->cart_contents as $key => $value) {
            $_product = $value['data'];

            if ($_product->get_id() == $free_product_id) {
                $value['data']->set_price($custom_price);
            }
        }
    }
}

add_action('woocommerce_before_calculate_totals', 'ts_add_custom_price');

Output

Though the regular price of the free product is $20 on the product page, the price gets changed to 0 when the same product gets added to the cart.

3. Modify the Free Product's original price to zero
3. Modify the Free Product's original price to zero

The function add_custom_price is hooked to the woocommerce_before_calculate_totals event using add_action. This ensures that the custom pricing logic is executed when WooCommerce calculates the cart totals.

The code iterates through the items in the cart using $cart_object->cart_contents. For each item, it retrieves the product data as $_product. It checks if the product’s ID matches the free product’s ID ($free_product_id).

A variable, $carttotal, is used to track the current cart total. It calculates the cart total, excluding the free product’s price. If the total surpasses the threshold, it sets the free product’s price to $0 using set_price.

4. Limit the Free Product quantity to only 1

When the store is offering a special promotion such as adding a free product to the cart, the store owner may wish to provide only one free product. In order to achieve this you should also ensure that each customer can only get one free sample, and not more than that.

The given code snippets below will restrict customers from adding more than one quantity of the free product, whereas the parent product can be increased to the ‘N’ number of quantities.

function ts_aapc_add_product_to_cart() {
    global $woocommerce;
    $cart_total = 100;

    if ($woocommerce->cart->total >= $cart_total) {
        if (!is_admin()) {
            $free_product_id = 1494; // Product Id of the free product which will get added to cart
            $found = false;

            // Check if the product is already in the cart
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];
                    if ($_product->get_id() == $free_product_id) {
                        $found = true;
                    }
                }

                // If the product is not found, add it to the cart
                if (!$found) {
                    WC()->cart->add_to_cart($free_product_id);
                }
            } else {
                // If there are no products in the cart, add it
                WC()->cart->add_to_cart($free_product_id);
            }
        }
    }
}

add_action('template_redirect', 'ts_aapc_add_product_to_cart');

add_filter('woocommerce_quantity_input_args', 'ts_set_limit_free_product', 10, 2);

function ts_set_limit_free_product($args, $product) {
    $free_product_id = 1494; // Product Id of the free product which will get added to the cart

    if (!is_cart()) {
        if ($product->get_id() === $free_product_id) {
            $args['max_value'] = 1; // Maximum quantity (default = -1)
        }
    } else {
        if ($product->get_id() === $free_product_id) {
            // Cart's 'min_value' is 0
            $args['max_value'] = 1;
        }
    }

    return $args;
}

Output

The provided result shows that when the “sun glass” free product gets added to the cart, the quantity of “sun glass” cannot be raised beyond 1.

  1. Checking the Cart Total and Adding the Free Product:
  • The ts_aapc_add_product_to_cart function is triggered when the template_redirect action occurs.
  • It first checks the cart’s total by accessing the global $woocommerce object and comparing it to the preset value of $cart_total (which is set at $100).
  • It identifies the specific free product by its Product ID (in this case, Product ID 1494).
  • Then, it checks if this free product is already in the cart. If found, the variable $found is set to true. If not found, it sets $found to false.
  • If the free product is not already in the cart (i.e., $found is false), it adds the free product to the cart using WC()->cart->add_to_cart($free_product_id).

2. Limiting the quantity of the Free Product:

  • The ts_set_limit_free_product function is used to set a limit on the quantity of the free product that can be added to the cart.
  • This function is applied using the woocommerce_quantity_input_args filter.
  • When customers view a product (not in the cart), it checks if the product is a free product (Product ID 1494). If so, it sets the maximum quantity to 1.
  • When customers are on the cart page, it also limits the maximum quantity to 1 for the free product.

5. Match the parent product quantity with the free product

This is in contrast to the above requirement. Sometimes, store owners would like to enhance the value of the promotion by matching the number of parent products to the number of free products, thus encouraging customers to purchase larger quantities.

The following code snippet will adjust the number of free products to match the quantity of the chosen parent product.

function ts_aaptc_add_product_to_cart( $item_key, $product_id ) {
    $product_category_id = 58; // sports category id

    $product_cats_ids = wc_get_product_term_ids( $product_id, 'product_cat' );

    if ( ! is_admin() && in_array( $product_category_id, $product_cats_ids ) ) {
        $free_product_id = 1494; // Product Id of the free product which will get added to cart
        $found = false;

        // check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $free_product_id ) {
                    $found = true;
                    $new_quantity = $values['quantity'] + $quantity; // Increase the free product quantity by the quantity of the added product.
                    WC()->cart->set_quantity( $cart_item_key, $new_quantity );
                }
            }

            // if product not found, add it
            if ( ! $found ) {
                WC()->cart->add_to_cart( $free_product_id );
            }
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $free_product_id );
        }
    }
}

add_action( 'woocommerce_add_to_cart', 'ts_aaptc_add_product_to_cart', 10, 2 );

// Add a new action hook for updating the free product quantity when the parent product quantity is updated
add_action( 'woocommerce_after_cart_item_quantity_update', 'ts_update_free_product_quantity', 10, 4 );

/**
 * Add this code snippet in the functions.php file of your currently active theme.
 * updating the free product quantity when the parent product quantity is updated on the cart page
 */
function ts_update_free_product_quantity( $cart_item_key, $quantity, $old_quantity, $cart ) {
    $parent_product_id = 58; // Replace 58 with the desired parent category ID.
    $free_product_id   = 1494; // Replace 1494 with the desired free product ID.

    // Check if the updated item belongs to the specified category.
    if ( $cart->cart_contents[ $cart_item_key ]['data']->get_category_ids() && in_array( $parent_product_id, $cart->cart_contents[ $cart_item_key ]['data']->get_category_ids(), true ) ) {
        // Loop through cart items to find the free product.
        foreach ( $cart->get_cart() as $key => $item ) {
            // If the free product is found, update its quantity.
            if ( $item['product_id'] === $free_product_id ) {
                $cart->set_quantity( $key, $quantity );
                break;
            }
        }
    }
}

Output

The following output demonstrates that when customers add the LED television parent product, with a quantity of 5, the number of free products (sunglasses) also adjusts to the same quantity of 5.

Automatic Free Product Addition or Update:

  • The woocommerce_add_to_cart hook is used, which triggers the ts_aaptc_add_product_to_cart function.
  • Within this function, if a product from the sports category (category ID 58) is added to the cart, it checks if the free product (Product ID 1494) is already in the cart and updates its quantity accordingly.

2. Keeping Free Product in Sync with Parent Product:

  • An additional action hook, woocommerce_after_cart_item_quantity_update, is added to update the free product’s quantity when the parent product’s quantity is modified in the cart.
  • The corresponding function, ts_update_free_product_quantity, is responsible for this synchronization.

Why this topic?

The idea of writing this post came from one of our clients using the Booking & Appointment plugin for WooCommerce for Tour Business. His requirement was when the customer is booking the tour they automatically add the company cap as a free product to their basket.

As you can see in the above gif, I have added a booking for the New York City All Around Town Hop-on Hop-off Tour by selecting the start date as 9th November 2017. Adding this booking to the cart is automatically adding the Cap product to the cart.

Conclusion

In this post, we have seen how easy it is to automatically add a product to your WooCommerce cart on a website visit, on the Add to Cart button click, and based on the total of the cart. There might be many other scenarios where the need arises to automatically remove the products from the cart.

Feel free to mention your questions in the comments below and we shall get back to you as early as possible.

Browse more in: WooCommerce Tutorials, Code Snippets, WooCommerce How Tos

Share It:

Subscribe
Notify of
143 Comments
Newest
Oldest
Inline Feedbacks
View all comments
dante
12 hours ago

hi, I would like to insert snippet two, when the cart total reaches a certain amount, add the free Product to the cart, when it reaches €30 you must add a product. How can I do it? Where should I insert the spinnets and how? Is there a plugin? I’m running some tests on a test site before putting it on the original site.

Thanks for the reply

Chris
24 days ago

Hi,

Great snippets of code here.

I am trying to add a product to the cart if a certain variation of product is added to cart.

Snippet 1 above only adds a product if the item is in a certain category.

I would like to do it for product_id. For example if either one of these products 123,124,125 gets added to cart then this product is added to cart.

Its like Snippet 4 but instead of categories I would like Products

Thanks
Chris

22 days ago
Reply to  Chris

Hi Chris, 
              Thanks for your appreciation! To address your specific need to add free products when certain variations of product IDs are added to the cart, you need to modify the first part of the ‘Code Snippet 1’ like this:

function aaptc_add_product_to_cart( $item_key, $product_id ) {


    $product_variation_ids = array( 21, 22, 29 ); // Replace these with your desired product variation IDs


    if ( ! is_admin() && in_array( $product_id, $product_variation_ids ) ) {


        $free_product_id = 28; // Product Id of the free product which will get added to cart


        $found = false;


1 month ago

Hello! First of all what a great site with solutions that are understandable… However do I have some issues with “1. Remove the Free product if the Parent product is removed”. The first part (adding the free product) is working like a charm but when I remove the parent product then the free product does not remove and keeps available in the shopping cart. I don’t know what I have done wrong. I have copied the entire code and only adjusted the category and product ID (on two places in the code; once to add the free product and once… Read more »

1 month ago

Hi Patrick,
I tried to reproduce the issue and the code works fine from my end. You have followed the right procedure of changing the product ID and product category ID. Just make sure whether you are removing the free product (with product ID) instead of the parent product(category ID). And further, if the issue persists, you need to look into any theme or plugin conflicts in your site.

Leonidas
2 months ago

Hello and many thanks for this extremely useful post.
Could you please add an “Auto Add Free Product based on Cart Total, Excluding Products with Specific Tag Terms”?Once again, thank you so much!

2 months ago
Reply to  Leonidas

Hi Leonidas,
The post has been updated in response to your requirement. Please refer to the code snippet under the heading ‘Auto Add Free Product based on Cart Total, Excluding Specific Product Tags.’

Leonidas
2 months ago
Reply to  Saranya

Wow! And so fast! I can’t thank you enough for your invaluable help!

Leonidas
2 months ago
Reply to  Saranya

I don’t mean to sound greedy but if it would be possible to add “Remove the Free product if the Parent product is removed by the user” in this scenario, it would be awesome. I’m afraid that all my efforts to write it myself were a failure. In any case, I would like to thank you once more!

2 months ago
Reply to  Leonidas

Hi Leonidas,

The post has been updated to address your follow-up requirement. Please refer to the code snippet under the heading ‘7. Auto-Add and Remove Free Product Based on Cart Total, Excluding Specific Product Tags in WooCommerce.

Leonidas
2 months ago
Reply to  Saranya

It works great! Thank you so much! Your help is invaluable!

Hary das cuellar
1 year ago

thank you very much it helped me a lot

4 months ago

That’s great to know, Hary!

143
0
Would love your thoughts, please comment.x
()
x