Apply a free shipping coupon when the cart contains only one item.
In the Advanced WooCommerce Facebook group a user asked:
I am looking for a coupon system with limits.
For example: free shipping coupon if cart only has one item in it.
Back in 2013 I wrote about automatically adding a coupon when multiple products were in the WooCommerce cart.
Struggling for something to write about this week I decided to tackle the task asked in the Facebook group.
How it works
When the plugin is activated the ‘register_activation_hook‘ code runs to create the coupon. The coupon description is set but never used – it’s there to explain the coupon when viewing it in the admin.
When the cart is viewed, the plugin checks the number of items in the cart. It adds the coupon if there is only one item and removes it if there is more than one item. In each case it checks whether the coupon is already present so it doesn’t add or remove the coupon twice and trigger a warning message that might confuse the customer.
The same section of the code also hides the ‘Coupon’ row of the cart page. This is because the default cart page (shown above) will expose the coupon code and you see ‘Free shipping’ twice.
If you want to leave the coupon information on the page you can unhide it by changing true to false in the plugin.
Additionally, when the coupon is added and free shipping now available, the other shipping methods are hidden. This is to prevent the user accidentally choosing a shipping method that has a charge.