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

How to Create a Free Sample With Every Purchase on the WooCommerce?

Are you looking for a different way to provide your WooCommerce store customers by offering free product samples? Look no further! The below code snippet adds a “Free Sample” feature to your product pages, allowing users to easily add a product to their cart.

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.

How to Create a Free Sample With Every Purchase on the WooCommerce? - Tyche Softwares

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 Create a Free Sample With Every Purchase on the 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 Create a Free Sample With Every Purchase on the 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