Honor the greater discount with a shopify script

New Member
3 0 0

Hi there. I want to create a script that applies, for example, 30% off the original line item price, unless the sale (current) price would be a better deal.

Not sure where to start, and I'm not sure if I even have access to the original (compare at) price. 

Looking at the API guide, I'm not sure if original_line_price is the compare at, or if it's just the price before all scripts and codes.

Thanks for any help!

Replies 3 (3)
Shopify Partner
132 1 21

Hi Robert,


This should do the trick. It will apply the logic to all items in the cart, whether the item is on sale or not. You can remove the else if you want to only apply the discount logic to items that are currently on sale.


discount_percent = 51
discount_message = "This discount is the best!"

Input.cart.line_items.each do | item |
  if !item.variant.compare_at_price.nil? && item.variant.compare_at_price.cents > 0
    #Item is on sale, compare prices
    discounted_price = item.variant.compare_at_price.cents * ((100-discount_percent)/100)
    if discounted_price < item.original_line_price.cents
      #If the discounted price is less than the current sale price, then apply the discount
      item.change_line_price(Money.new(cents: (item.variant.compare_at_price.cents * ((100-discount_percent)/100))), { message: discount_message })
    #Item isn't on sale, apply discount directly
    item.change_line_price(Money.new(cents: (item.original_line_price.cents * ((100-discount_percent)/100))), { message: discount_message })

Output.cart = Input.cart

Hope that helps!




Feeling a bit lost? Contact elliot@mandelbrotian.com for help with theme setup, alterations, custom functionality, and app development.
New Member
3 0 0

Wow, Elliott! That is amazing. I did not expect the full solution!

Can't thank you enough! I'll send an email your way a little later with some questions

New Member
1 0 0


Thank you for this!  How can I change the display strike out price from `line_item.line_price` to `line_item.variant.compare_at_price` ?