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

How to Add a Free Sample Product With Every Purchase in WooCommerce?

Are you looking for a unique way to delight your WooCommerce store customers by offering free product samples? Look no further! Implementing the following snippet will allow your customers to easily add a free sample product to their cart. Let’s see how it’s done!

Solution: Add a Free Sample Product With Every Purchase in WooCommerce

The below code snippet adds a button labeled “Order a Free Sample Product” to the product pages. This button allows customers to easily add a specific free product to their cart by clicking it.

add_action( 'woocommerce_single_product_summary', 'ts_add_free_sample_add_cart', 35 );
  
function ts_add_free_sample_add_cart() {
   ?>
      <form class="cart" method="post" enctype='multipart/form-data'>
      <button type="submit" name="add-to-cart" value="34" class="single_add_to_cart_button button alt" style="background-color: #FFBF43">Order a Free Product</button>
      <input type="hidden" name="free_sample" value="<?php the_ID(); ?>">
      </form>
   <?php
}
  
add_filter( 'woocommerce_add_cart_item_data', 'ts_store_free_sample_id', 9999, 2 );
  
function ts_store_free_sample_id( $cart_item, $product_id ) {
   if ( isset( $_POST['free_sample'] ) ) {
         $cart_item['free_sample'] = $_POST['free_sample'];
   }
   return $cart_item; 
}
  
add_filter( 'woocommerce_cart_item_name', 'ts_alter_cart_item_name', 9999, 3 );
  
function ts_alter_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
   if ( 34 === $cart_item['product_id'] ) {
      $product = wc_get_product( $cart_item["free_sample"] );
   }
   return $product_name;
}

Output

When a customer adds the product i.e. “Hoodie with Logo” to their cart on the single product page, they can also add a free sample product by clicking the button below.

Add a Free Sample Product

Upon redirecting to the cart page, the customer will see two products: a Hoodie with a Logo and a free sample product – a Tshirt with Logo.

How to Add a Free Sample Product With Every Purchase in WooCommerce? - Tyche Softwares

It also displays two products on the checkout page, i.e. Hoodie with Logo and a free sample product (Tshirt with Logo)

How to Add a Free Sample Product With Every Purchase in WooCommerce? - Tyche Softwares

Similarly, you can also automatically add a product to your WooCommerce cart page based on various conditions such as limiting the free product to one quantity and setting the free product price to zero.

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

Share It:

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x