skip to Main Content

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?

2

Answers


  1. Chosen as BEST 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
    

  2. Discounts are easy. First… get the discount code from the cart. You know it applies to the whole cart. Now you have an amount, or percentage or whatever you gave the customer in the code. Now kicks in the beauty of the scripts.

    For each product, decide if it is discounted or not. If it is, apply the discount amount that you know from the discount code provided to the item. If it is a product not to be discounted, leave the price alone.

    You are paying big bucks for the scripting engine. If you cannot program it yourself, pay someone that can! You are way better off studying a working script to learn, that trying to outfox yourself.

    So you can in fact reject the discount code for the cart, but still discount products, some, not all, or others.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search