[Shopify Script] 2 or more variants within the same product ID get 10% off – Nivesh's blog
Published on

[Shopify Script] 2 or more variants within the same product ID get 10% off

Authors
Table of contents

Introduction


In this article, we are going to create a Shopify Script that gives 10% discount on the line items having at least 2 quantities of same product.

Requirements

2 or more variants within the same product ID get 10% off

Case 1:

  • Product A Variant 1
  • Product A Variant 2
  • Product A Variant 3

  Total 10% off

Case 2

  • Product A Variant 1
  • Product A Variant 2

  Total 10% off

Case 3

  • Product A Variant 1
  • Product A Variant 2
  • Product B Variant 1

  Only Product A (Variant 1+2) 10% off, not Product B

Case 4

  • Product A Variant 1
  • Product B Variant 1

  No discount

Final code

# Settings
DISCOUNT_PERCENTAGE = 10;
DISCOUNT_MESSAGE = "Bulk Discount";
MINIMUM_QUANTITIES = 2

# Code starts here
products_by_quantity = {};

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next if product.gift_card?

  if products_by_quantity[product.id]
    products_by_quantity[product.id] += line_item.quantity;
  else
    products_by_quantity[product.id] = line_item.quantity;
  end
end

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next if product.gift_card?

  if products_by_quantity[product.id] >= MINIMUM_QUANTITIES
    line_item.change_line_price(line_item.line_price * ((100 - DISCOUNT_PERCENTAGE) / 100), message: DISCOUNT_MESSAGE);
  end
end

Output.cart = Input.cart

I've got more coming...

Want to hear from me when I add new post? Sign up for my newsletter and I'll email you every time I post a new article. (I'll never share your email and only send you updates about new articles.)