Add Free Product When Coupon Code is Applied

This PHP code adds a product to the cart when a coupon code is applied in WooCommerce. in this example, we add a free product with the id of 14646 when coupon 30OFF is applied with a 30% discount.

To create a discount code in WooCommerce that provides a percentage discount and automatically adds a specific product to the cart when the coupon is applied, you can use the coupon functionality native to WooCommerce and custom PHP code.

Here are the steps:

1. Create a Free Product :

  • In your WooCommerce dashboard, go to Products > Add New.
  • Create a new product that will be offered for free. Set the regular price to 0.

2. Create a Coupon Code :

  • Go to WooCommerce > Coupons.
  • Click on Add Coupon.

3. Configure the Coupon :

  • Set the coupon code (e.g., “30OFF”).
  • Set the discount type to Percentage Discount and enter 30 in the amount field.

4. Add Custom Code :

  • Using FTP, navigate to your child themes functions file.
  • Open the functions.php file of your child theme.
  • Add the following code at the end of the file :
  • Alternatively, use a code snippets or custom functionality plugin and add the code there instead.

Swap out 14646 with the ID of the free product you created.

5. Save Changes :

Save the changes to your functions.php file.

Review

Using the code? If you are using the code from this post, please leave a review.

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.