Skip to content

Instantly share code, notes, and snippets.

@craigcooperxyz
Created November 2, 2023 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigcooperxyz/d0f419699e980118a9ca383437f083e8 to your computer and use it in GitHub Desktop.
Save craigcooperxyz/d0f419699e980118a9ca383437f083e8 to your computer and use it in GitHub Desktop.
Automatically add a discount code cookie to a Shopify customer's basket when they land on the page. Useful if you need to apply a discount, but can't use automatic discounts. A bit like using the link Shopify provide, but without the need for the link. Also; will check for existing discount cookie before applying.
(function() {
const discountValue = 'DISCOUNTCODEHERE';
const daysToExpire = 7;
let discountCode;
if (document.cookie.includes("discount_code=")) {
discountCode = document.cookie.split('; ').find(row => row.startsWith('discount_code=')).split('=')[1];
console.log("Discount code is: " + discountCode);
} else {
const date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = `discount_code=${discountValue}; expires=${date.toUTCString()}; path=/`;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment