less than a minute read • Updated 9 minutes ago
Add or remove a coupon based on items in the cart
How to automatically add or remove a coupon when a required product is added to or removed from the cart.
If you have a promotion that you're offering, such as "purchase x product and receive x off of x product", you'll want to make sure that the user can't override the purchase requirement by adding the required product, receiving the discount on the second product, then removing the original required product.
This snippet looks for the presence of a specific coupon (based on the code), and the total quantity of any products with a specific code. Then if the coupon is there but the products are not, it removes the coupon. If it has the products, but not the coupon, it adds it. This logic is run on page load of the checkout, along with whenever a product is removed, quantity updated or coupon added on the checkout. This should then ensure that the coupon is only present when the required conditions are met.
The script is based on the quantity of a specific product code - but it can be adjusted as needed, whether you need it for a specific category of products, or a specific total order amount of specific products rather than quantity.
Step 1: Apply the snippet to your configuration
In the Foxy admin (https://admin.foxy.io), go to Settings > Templates and add the code to the Custom footer field (Twig is supported; it is injected before the closing </body> tag).
{% if context == "checkout" %}
<script>
FC.client.on("ready.done", checkPromoProducts);
FC.client.on("cart-item-remove.done", checkPromoProducts);
FC.client.on("cart-item-quantity-update.done", checkPromoProducts);
FC.client.on("cart-coupon-add.done", checkPromoProducts);
function checkPromoProducts() {
var coupon_code = "COUPON_CODE",
product_a_qty = 0,
coupon_id = 0;
if (FC.json.coupons.hasOwnProperty(coupon_code)) {
coupon_id = FC.json.coupons[coupon_code].id;
}
for (var i = 0; i < FC.json.items.length; i++) {
if (FC.json.items[i].code == "PRODUCT_CODE") {
product_a_qty += FC.json.items[i].quantity;
}
}
if (coupon_id > 0 && product_a_qty == 0) {
// The coupon shouldn't apply anymore
FC.client.request("https://" + FC.settings.storedomain + "/cart?cart=remove_coupon&coupon_code_id=" + coupon_id).done(function(dataJSON) {
FC.cart.render();
});
} else if (coupon_id == 0 && product_a_qty > 0) {
// They should have the coupon, let's add it
FC.client.request("https://" + FC.settings.storedomain + "/cart?coupon=" + coupon_code).done(function(dataJSON) {
FC.cart.render();
});
}
}
</script>
{% endif %}Step 2: Customize conditions
You'll also need to update the coupon code string in the script (it's near the top as "COUPON_CODE") and the product code string too (shown as "PRODUCT_CODE") to the coupon code you created.