Skip to content

Instantly share code, notes, and snippets.

@ccashwell
Last active January 19, 2023 15:25
Show Gist options
  • Save ccashwell/38cc80a977adaf1777fc6668bd438f28 to your computer and use it in GitHub Desktop.
Save ccashwell/38cc80a977adaf1777fc6668bd438f28 to your computer and use it in GitHub Desktop.
Autofill Discount Code from Shopify URL
<script>
/* Put this in theme.liquid, preferably right before "</body>" */
(function() {
var discountParam = document.location.search.match(/discount=(\w+)/);
if (discountParam && discountParam.length > 1) {
document.cookie = discountParam[0];
}
})();
</script>
<script>
/*
Put this in cart.liquid, preferably at the bottom of the file.
Also, make sure your cart's "<form>" has an ID of "cartform".
*/
(function() {
var discountCookie = document.cookie.match(/discount=(\w+)/);
if (discountCookie && discountCookie.length > 1) {
document.getElementById('cartform').action = '/cart?' + discountCookie[0];
}
})();
</script>
@pojitonov
Copy link

pojitonov commented Aug 18, 2017

For some reason it works only when I redirect customer to main page (e.g. www.site.com/?discount=CODE). When I do the same to other pages e.g. Product Catalog (www.site.com/collections/all/?discount=CODE), it not working.

@michaelrosario
Copy link

michaelrosario commented Nov 22, 2017

For now, I updated the following code to update the "Add to Cart" button so that the discount gets added to the URL. This works for me on the District Theme. I'm sure there is a better way to implement it.
`<script>
/* Put this in theme.liquid, preferably right before "" */
(function() {
var discountParam = document.location.search.match(/discount=(\w+)/);
if (discountParam && discountParam.length > 1) {
document.cookie = discountParam[0];
}
var discountCookie = document.cookie.match(/discount=(\w+)/);
if (discountCookie && discountCookie.length > 1) {
document.getElementById('CartButton').href = '/cart?' + discountCookie[0];
}

})();
</script>`

@zzhangm
Copy link

zzhangm commented Apr 16, 2019

To make this work on all pages, you need to add ;path=/ to the cookie string so that the cookie can apply to all paths under the domain.

That is, use the following snippet. Works nicely on our Shopify store.

<script>
  /* Put this in theme.liquid, preferably right before "</body>" */
  (function() {
    var discountParam = document.location.search.match(/discount=(\w+)/);
    if (discountParam && discountParam.length > 1) {
      document.cookie = discountParam[0] + ";path=/";
    }
  })();
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment