Automatically add a coupon to the cart

Currently Foxy coupons require the customer add them to the cart using a code on the cart or checkout. Sometimes though you'd like to offer a discount automatically to your customers, without them needing to add a code.

To do that, you can add a small bit of javascript to your own website (not your store templates), that looks like this:

<script>
var FC = FC || {};
FC.onLoad = function () {
    FC.client.on('ready.done', function () {
        var code = "YOUR_COUPON_CODE";
        if (!FC.json.coupons.hasOwnProperty(code)) {
            FC.client.request('https://'+FC.settings.storedomain+'/cart?coupon=' + code).done(function() {
                if (FC.util.hasError('coupon')) {
                    FC.util.removeError('coupon');
                }
            });
        }
    });
}
</script>

Include that code on your own website, making sure that you're also including the loader.js file for your store. Within that code, you will also need to update the YOUR_COUPON_CODE value to be the code for the specific coupon you're wanting to add automatically.

This script will also clear out any error that may be returned when trying to add the coupon to the cart in the background. This could happen for example if the code doesn't match a coupon for your store, or the coupon isn't active based on the start/end dates.

Optional: Add from the cart/checkout too

The above script will just check if a coupon is present when each page loads on your website, and add the coupon in the background. If you want to ensure that the customer has that coupon still when they reach the checkout (for example, if they accidentally removed it or cleared their cart), then you can use the following code.

Include this code in the “footer” textarea of the “Add custom header and footer code to your templates” option, found on the “configuration” page in your store's FoxyCart administration:

{% if context == "cart" or context == "checkout" %}
<script>
function addCoupon() {
    var code = "YOUR-COUPON-CODE";
    if (code != "" && !FC.json.coupons.hasOwnProperty(code)) {
        FC.client.request('https://'+FC.settings.storedomain+'/cart?coupon=' + code).done(function() {
            if (FC.util.hasError('coupon')) {
                FC.util.removeError('coupon');
            }
            FC[FC.json.context].render();
        });
    }
}
 
FC.client.on("ready.done", addCoupon);
FC.client.on("cart-coupon-remove.done", addCoupon);
{% if context == "cart" and not cart_is_fullpage %}
    if (typeof cart_callback == "undefined") {
        FC.client.on("cart-submit.done", addCoupon);
        cart_callback = true;
    }
{% endif %}
</script>
{% endif %}

As with above - you'll need to update that script to replace YOUR_COUPON_CODE with your actual code.

Site Tools