Buy 2 items and get 20% , but exclude some products

Highlighted
Shopify Partner
4 0 0

Hi.

I have this script, that gives 20% discount if a customer buys 2 items and more.

I works fine, but I have some products (product_type == "Charity" or product_type == "POS") I would like to exclude from the eligible products, to get the discount.

# Message:
  message = "Buy 2 items and get 20%"
# Discount:
  discount = 20
# Quantity:
  discount_quantity = 2 # items needed in cart to get the discount

#Variables:
  # Create an array of all line item quantities
  cart_quantity_array = Input.cart&.line_items&.map { |item| item.quantity }
  # Sum the line item quantities
  cart_quantity = cart_quantity_array.reduce(0, :+)

#Calc:
  discount_percent = if cart_quantity >= discount_quantity
    discount / 100
    else
    0
  end

Input.cart.line_items.each do |line_item|

  line_item.change_line_price(line_item.variant.compare_at_price * line_item.quantity * (1-discount_percent), message: message) unless discount == 0
end

Output.cart = Input.cart

I have tried this:

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next if product.gift_card?
  next if product.product_type == "Charity"
  next if product.product_type == "POS"

But that just jumps over the products, not giving the discount one the "next" products, but stille the rest.

If a customer buys 2 products: one eligible product and one not (product_type == "Charity") the customer still gets the discount on the eligible product.

How do I make it so that doesn't happen?

 

Hope it makes seens :)

Thanks in advance.

0 Likes