My solution for discounting existing cart products using 'trigger' product

JCAndrea
Shopify Partner
34 1 9

I needed a way to sell several of my 'membership' products, as well as discount other products in the cart (but i did NOT want to discount any of the membership products) the 10% member discount. Also, I have thousands of products, but only a handful that do NOT allow a member discount. I couldn't find any apps that utilized both a 'trigger' product, as well as the ability to NOT allow discounts on the actual 'trigger' product.

So, I developed a script to do this, and the mechanism to control it is simply product tags. Tagging several of my Membership products with 'membership' as well as tagging them with 'no member discount.' I then tagged the handful of other products in my catalog that i do NOT allow the member discount on... also with 'no member discount.'

The code isn't super scalable, but it's more of a jumping off point for bigger things.

Anyway, here it is, and hope it helps!

Also, I utilize a different app for discounting items for existing, logged-in 'members,' (customers tagged with 'member') but I may be moving to using Script Editor to handle this in the future because it has much less overhead than what I'm currently utilizing for that.

Jason

 

 

 

#set indicator for membership exists in the cart
cart_contains_membership = false

Input.cart.line_items.each do |line_item|
    #loop over cart items to see if any product is tagged with 'membership'
    product = line_item.variant.product
    next if product.gift_card?
    next unless product.tags.include?('membership')
      #this product is tagged with 'membership'
      cart_contains_membership = true
end

if cart_contains_membership == true
  #loop over all products again and discount all items in cart
  #unless the product is tagged with 'no member discount'
  Input.cart.line_items.each do |line_item|
    product = line_item.variant.product
    next if product.gift_card?
    next unless product.tags.include?('no member discount') == false
      line_item.change_line_price(line_item.line_price * 0.90, message: "Member Discount")
  end
end

Output.cart = Input.cart