Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Shopify script for applying an upper limit on total discount amount based on cart value. Will spread the maximum discount amount proportionately across all cart products. Applies percentage discount to cart products under cart value threshold.
# In this campaign we wanted to have 50% of every product unless the cart value was 200 or more
# If the 200 or more, the maximum discount that could apply was 100
# Wanted to spread that the discount amount across all line items proporinate to its value in the cart
# Do/change following (if required):
# 1. Create a new coupon code in Shopify
# 2. Replace the coupon code evaluation value ('DISCOUNT_CODE') with the new code on line 13
# 3. Change the cart subtotal evaluation amount ( on lines 16, 39
# 4. Change the max_discount value (100) on line 18
# 5. Change the discount amount (0.5) on line 41
# Check the cart has a discount code and if so it equals the campaign
if Input.cart.discount_code and Input.cart.discount_code.code == 'DISCOUNT_CODE'
# Conditions for when the maximum discount value applies, in this case 200 or more
if Input.cart.subtotal_price >=
# Value of the maxium discount that the cart will have
max_discount = 100
# Get Float value of the cart's cents variable in dollars
cart_subtotal_float = Float((Input.cart.subtotal_price.cents / 100).to_s)
# For each line item
Input.cart.line_items.each do |line_item|
# Get Float value of line item's cents variable in dollars
line_price_float = Float((line_item.line_price.cents / 100).to_s)
# Calculate percentage the line items price should be reduce to, achieved by:
# 1. Divide the line price by the cart to get the percentage of the cart it represents
# 2. Multiple the percentage by the max discount amount to get the value the line item needs to be reduced by
# 3. Find the percentage the line item needs to be reduced by
# 4. Minus the percentage the line item needs to reduce by from 1 to get end percentage value the line item needs to be
percentage = 1 - (((line_price_float / cart_subtotal_float) * max_discount) / line_price_float)
# Multiple the line item by the percentage value it needs to be
line_item.change_line_price(line_item.line_price * percentage, message: "")
# If they are under the threshold reduce every line item by 0.5 (50% off)
elsif Input.cart.subtotal_price <
Input.cart.line_items.each do |line_item|
line_item.change_line_price(line_item.line_price * 0.5, message: "")
Output.cart = Input.cart

This comment has been minimized.

Copy link

@jimmijazz jimmijazz commented Nov 19, 2019

You may want to add in a check for $0 items if you're using this. Line 35 caused errors

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment