— March 14, 2018
While working on a Shopify problem (applying a discount code to the highest priced item), I found this page (https://ecommerce.shopify.com/c/shopify-apis-and-technology/t/apply-discount-to-most-expensive-item-in-cart-464958). There’s a lot of discussion on the page, but the examples repeatedly use
line_item.change_line_price(high.variant.price * 0.80, message: "discount").
This is wrong, as line_price is the line item price, not the variant price. It is the initially defined as the quantity * variant.price, though obviously the discount is setting it to whatever you want. You can test this difference by setting the quantity to anything higher than 1.
I tried posting this to that discussion, where it might actually do some good, but either it is too old to accept new entries or my post didn’t get moderated. (or I got logged out while looking at it. I was logged in when I started, but noticed when I went back the next day to look at the link I put in the post that I was not logged in, and the post was not there.)
Here’s the complete code. The editor complains about “Discount code requirements not met (empty cart)”, but seems to work with a full/empty discounted/not cart in the test. Please let me know if you can see why it does that! Given you can only put in the discount code on the checkout page, I don’t see how you can get meet code requirements with an empty cart, anyway.
#you must also make a discount named "25% off 1 item". It should not do anything (0% off is good). if Input.cart.line_items.length > 0 if Input.cart.discount_code != nil && Input.cart.discount_code.code == '25% off 1 item' high = Input.cart.line_items Input.cart.line_items.each do |line_item| if high.variant.price < line_item.variant.price high = line_item end end Input.cart.line_items.each do |line_item| if high == line_item if line_item.quantity > 1 new_line_item = line_item.split(take: 1) new_line_item.change_line_price(new_line_item.line_price * 0.75, message: "25% Off of 1 Item Only.") Input.cart.line_items << new_line_item else line_item.change_line_price(line_item.line_price * 0.75, message: "25% Off of 1 Item Only.") end end end end end Output.cart = Input.cart