Shopify Script, Buy Product from vendor X get Product Y for free

In shopify I was looking for a way to get a free product when buying from a specific vendor, I came up with below script.
In our case we also needed the vendor’s product to be at > $400 for the gift product to be free, you can offcourse remove that if statement.
Unfortunately you can’t add products to the cart with shopify scripts (yet?) so¬†you can leave adding the product up to the customer, or add the product with javascript in the frontend.

You can remove the puts statements, I though I’d leave them so you can see how to debug something like this.

discounted_product = 2228740609
products_seen = false;

puts('loop over all products, and check if we have the required vendor')
Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  if(product.vendor.downcase == 'vendorname')
    if(line_item.variant.price > 40000))
      puts('found a product matching vendor, and matching minimum price of $400')
      products_seen = true;

  puts('Check if the gift product is in the cart, and update its price to 0')
  Input.cart.line_items.each do |line_item|
    product = line_item.variant.product
    next unless == discounted_product
      puts('they will only get 1 free, not unlimited items')
      updated_price = line_item.line_price.cents - (line_item.line_price.cents / line_item.quantity)
      line_item.change_line_price( updated_price) , message: "Free Shoetrees")

Output.cart = Input.cart


Leave a Reply

Your email address will not be published.