Ad

Block Discount On Certain Product Shopify Script

- 1 answer

I want to write a script in Shopify that prevents discounts from rendering on certain products. I know this is wrong, but something like this:

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product

  if product = 123456789
     CartDiscount.remove("Discount does not apply")
  end

end

Output.cart = Input.cart

I looked at the documentation and saw the .reject({ message: String }) method but it applies to the whole cart. Is there a way to localize this to one instance?

Ad

Answer

Old question but I found a resolution: basically, you can't "localize" a discount to a specific product. You have to block the entire cart from getting a discount. The approach I ended up taking is below:

# ID of product you want to block
productId = 10199241991

# Runs through a loop of items in your cart
Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  puts product.id
  next if product.gift_card?
  next unless product.id == productId
  case Input.cart.discount_code
  when CartDiscount::Percentage
    Input.cart.discount_code.reject({message: "Cannot be used with this product"})
  end
end


Output.cart = Input.cart
Ad
source: stackoverflow.com
Ad