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.
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.
It also displays two products on the checkout page, i.e. Hoodie with Logo and a free sample product (Tshirt with Logo)
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.