Reliable way of adding discount code to cart from Liquid

I have a very specific set of criteria for automatically adding discount codes to the cart which requires me to code this right into my cart.liquid file instead of using the automated discounts built into Shopify.

Here is the code I am using to add the discount when conditions are met:

It seems very simple but for some reason, depending on the day, anywhere between 50-75% of orders that should get the discount do not. I have put in some tracking code to confirm that this line of code is in fact being run in each of the cases but for some reason, it just simply doesn’t apply the discount code.

Has anyone else encountered this type of sporadic behavior with discount codes and is there a more reliable way of automatically adding them?

Hi @storebot

Please follow these steps:

  • Go to Edit Theme Code > The theme.liquid file, and add the following code right after the tag:
{% if template.name == 'index' %}

{% endif %}
  • Go to the file cart-template.liquid (or main-cart.liquid), and add the following code at the end of the file:
{% javascript %}
$(document).ready(function() {
    var discount = sessionStorage.getItem('discount');
    if (discount !== null) {
        var el = $('#input-discount');
        el.prop('readonly', true);
        el.val(discount);
    } else {
      el.val("");
    }
});
{% endjavascript %}
  • Add the following code inside the form tag:

I hope that it will work for you.

1 Like

Hi @BSS-Commerce ,

Thank you for the detailed steps! I have implemented this and let it run for a few days and we are seeing less of the issue but it’s still present on a small percentage of orders. Looking to close that gap if you have any other suggestions.

It looks like the remaining issues that we have are with ShopPay and PayPal Express. Any thoughts on how to solidify the process with them?

Hi @storebot

The above solution depends on several cases. For some unknown cases, it can lead to problems that prevent a small part of orders from being automatically discounted by discount codes. If you still want to use discount codes as a form of discount automatically for customers when ordering, you can consider using the Custome Pricing module of the B2B Wholesale Solution app.

I hope that it will be useful for you.