Add a product to the cart when a discount code is used
Automatically add a free product when a customer enters a certain discount code, and remove it again if the code goes, with Custom HTML.
Last updated
When a customer enters a code like FREESAMPLE, this Custom HTML script adds the matching product to the cart, and removes it again if the code is removed or the cart is emptied. Rewards can't trigger on a discount code, so this is a case for Custom HTML (Professional plan).
Before you start
- A Shopify discount that makes the product free. The script only puts the product in the cart; the price comes from Shopify. For example, create a discount code FREESAMPLE with 100% off the sample product, limited to one use per order if you like.
- The variant ID of the product to add. See Find a product's ID and variant IDs.
- Recommended: give the product the tags
_elite_hide_quantity_selectorand_elite_exclude_from_reward_calculation, so customers can't change its quantity and it doesn't count toward reward thresholds. See Use product tags to customize cart appearance.
Add the script
Use the general scripts position
Go to Cart designerCustom HTML and tick Enable on Top of cart & general scripts. This position runs even when the cart is empty, which a script that watches the cart needs. Leave Widget mode off.
Generate or paste the code
Either ask the AI generator, with Extended thinking (for complex tasks) ticked: "When the discount code FREESAMPLE is in the cart and the cart has other products, add variant 12345678901234 once with a marker property. Remove that line when the code is removed or it's the only item left." Or paste the code below and change the two values at the top.
Save and test
Click Save. On your store, add a product, enter the code in the discount field and check that the product is added at the discounted price. Remove the code and check that the product goes too.
Example code
<script>
(function () {
if (window.__ecCodeProductInit) return;
window.__ecCodeProductInit = true;
var DISCOUNT_CODE = "FREESAMPLE"; // your code, any letter case
var VARIANT_ID = 12345678901234; // the product to add
var MARKER = "__ecCodeProduct"; // marks the line this script added
var isProcessing = false;
function hasCode(cart) {
return (cart.discount_codes || []).some(function (discount) {
return discount.code && discount.code.toUpperCase() === DISCOUNT_CODE.toUpperCase();
});
}
function isOurLine(item) {
return item.properties && item.properties[MARKER];
}
async function sync(cart) {
if (isProcessing || !cart || !cart.items) return;
isProcessing = true;
try {
var ourLine = cart.items.find(isOurLine);
var otherLines = cart.items.filter(function (item) { return !isOurLine(item); });
var shouldHaveIt = hasCode(cart) && otherLines.length > 0;
var root = window.Shopify.routes.root;
var res = null;
if (shouldHaveIt && !ourLine) {
var line = { id: VARIANT_ID, quantity: 1, properties: {} };
line.properties[MARKER] = "1";
res = await fetch(root + "cart/add.js?elitecart=1", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [line] })
});
} else if (!shouldHaveIt && ourLine) {
res = await fetch(root + "cart/change.js?elitecart=1", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: ourLine.key, quantity: 0 })
});
}
if (res && res.ok) await window.EliteCart.refreshCart();
} catch (error) {
console.warn("[Custom HTML] Discount product sync failed", error);
} finally {
isProcessing = false;
}
}
function start() {
sync(window.EliteCart.getCurrentCart());
window.EliteCart.onCartChange(sync);
}
(function waitForEliteCart() {
if (window.EliteCart && window.EliteCart.onCartChange) return start();
setTimeout(waitForEliteCart, 50);
})();
})();
</script>
How it works
- The script checks the cart on load and after every change. It only adds the product when the code is entered and there's at least one other product, so a cart can't consist of the free item alone.
- The added line carries a hidden marker property. The script only removes lines with that marker, so if a customer buys the same product on purpose, that line is left alone. Properties starting with
_aren't shown to customers in the cart or at checkout. - Every cart request has
?elitecart=1and is followed by a cart refresh, so EliteCart doesn't treat it as a change by another app. The rules behind this are in Custom HTML for developers.
Still stuck?
Chat with us and we'll help you get your cart live. Or email contact@elitecart.app.