Goal: Be able to add ?discount=yourDiscountCode to any shop url and have that discount added to checkout automatically.
This code uses regex to parse the url and extract the urlParams into an object. It then uses local storage to store the discount code until the user reaches the cart page, then adds it to the cart form action.
If the user loads a new url with a different discount code, the new code will replace the old one. This allows stringing queries, so for example http://yourstore.com?someOtherQuery=thisValue&discount=yourDiscount
will still add yourDiscount
.
I chose to use localStorage rather than sessionStorage, so that if the user accidentally closes the tab and reopens it, they will still have their discount kept and applied. The localStorage discount is removed after two hours of non-use.
-
Add
checkout-auto-discounts.liquid
to your snippets and include it at the bottom of<body>
:{% include 'checkout-auto-discounts' %}
. -
Make sure your cart
<form>
has an id ofcartform
. If you wish to use a different id or class, be sure to updatecheckout-auto-discounts.liquid
accordingly. -
Test by adding a discount query param and seeing if it works!