shopifyliquidshopify-template

How to add an automatic discount to customers tags or segments in Shopify theme code


How can I get Shopify to automatically add a discount code, but only for customers with specific tags?

It used to be possible to add discounts with a discount GET parameter. This could be conditionally added depending on customer tags, like so:

{% if customer.tags contains 'special-tag' %}
    <input type="hidden" name="discount" value="DISCOUNTCODE"/>
{% endif %}

However, following an update to Shopify's checkout system, this no longer works.

How can discount codes be added automatically, depending on a customer's tags? This should be done in liquid theme templates rather than a Shopify app.


Solution

  • Shopify will apply a discount code if the customer visits the URL "/discount/code-name". As an example, if the code is DISCOUNTCODE and a customer goes to https://your-shop.com/discount/DISCOUNTCODE then the code gets added to their cart.

    Shopify doesn't care if the customer manually goes to that URL or if the URL is called from JavaScript. As long as the user cookie is set, it knows what customer to add the discount to. So we can use JavaScript to visit that URL in the background when the cart page loads, and the relevant discount code will automatically be applied. We can also only load the JavaScript if the customer has a specific tag (or any other condition).

    This must be done on the cart page.

    In a theme liquid file that's displayed on the cart page (most themes have a cart.liquid template or section), put:

    {% if customer.tags contains 'special-tag' %}
        <script>
            try { fetch( '/discount/DISCOUNTCODE' ) }
            catch(e) {}
        </script>
    {% endif %}
    

    The frontend script will only be run for customers who have the special-tag tag, meaning automatic discounts can be limited to a specific customer segment.