How to apply a global discount to your WooCommerce store

I had a client who wanted to apply a global discount on his WooCommerce store. Rather than looking for a plugin, and adding extra features I’d probably wasn’t going to use anyway. I decided to jump in to the WooCommerce source and have a look on how I could pull this off.

Inside the WooCommerce plugin folder I’ve found a function add_discount inside the WC_Cart class. The comment clearly tells me what it does:

* Applies a coupon code passed to the method.
* @param string $coupon_code - The code to apply
* @return bool True if the coupon is applied, false if it does not exist or cannot be applied

Aha, we are on to something!

Adding our coupon to the cart

To make sure every customers gets the discount we need this coupon code to be applied immediately to the cart. Sure, we could’ve made the choice of letting them enter the coupon code manually, but then this wouldn’t be a global discount, right?

We got our [f=”add_discount”] function. Now we only need a way to automatically add it to our customers cart.

By using the following hook [h=”woocommerce_add_to_cart”] we can run our own defined function every time somebody adds something to his/her cart.

By adding following code to our functions.php file we get the desired result.

I’ve also did a check to make sure the coupon gets only applied after adding the first product to the cart. This way the coupon code can still be removed if needed. Although I don’t know why you would remove discounts anyway…