Back to Blog

2018-12-09

shopifyscripts

How to Give an Automatic Discount on Shopify Based on Cart Value

How to Give an Automatic Discount on Shopify Based on Cart Value

One of the biggest issues I have seen with scripts is that it is really easy to give discounts based on line item value, but calculating the cart value, and applying logic based on that is causing a lot of people issues. Here is a REALLY easy way to solve for this and I will give two examples.

1. $X Off if Cart is over $Y

This will give the customer a discount of $5 if the cart is over $30.

min_discount_order_amount = Money.new(cents:100) * 30

total = Input.cart.subtotal_price_was

discount = if total > min_discount_order_amount
  500
else
  0
end

message = "My message"

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next if product.gift_card?
  line_item.change_line_price(line_item.line_price - Money.new(cents: discount), message: message) unless discount == 0
end

Output.cart = Input.cart

2. Variable discount depending on cart value

This will give the customer a discount of $5 if the cart is over $50 OR will give them $10 off if the cart is over $100.

min_discount_order_amount = Money.new(cents:100) * 50
min_discount_order_amount_2 = Money.new(cents:100) * 100

total = Input.cart.subtotal_price_was

discount = if total > min_discount_order_amount_2
  1000
elsif total > min_discount_order_amount
  500
else
  0
end

message = "My message"

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next if product.gift_card?
  line_item.change_line_price(line_item.line_price - Money.new(cents: discount), message: message) unless discount == 0
end

Output.cart = Input.cart

As always, let me know if there are any questions in the comments.