Woocommerce

Add Free product to woocommerce cart automatically ( without a plugin )

One of our clients want to provide a free product ( Price: $0 ) to their customers if they have some products already in their cart. Custom code looked prominent solution for that use case. We have searched in google and found some logic with code and we have altered it as per our use case

We have implemented as below

1) Add that particular free product to user’s cart once user add any product to their cart

2) Check and remove that particular free product if user removed all products
from their cart ( It prevents user to order only that free product without any other products in the cart )

Step 1: Adding Free product to cart once user add any product to their cart:

The below code will added that free product to cart once user add any product to their cart. If that free product was added already, then it won’t add that free product once again.

Step 2: Check and remove that particular free product if user removed all products from their cart

 

The above code will check the user cart when they visit cart page or checkout page. If they have other product apart from free product in their cart, then it will allow to proceed on checkout otherwise, it will remove that free product from the cart and cart will be empty.

If you like to use these code, change that value of variables ‘$product_id’ and ‘$prod_to_remove’ to your free product id and paste these codes in your theme functions.php.

Leave a Reply

Your email address will not be published. Required fields are marked *