Is deleting a line item from cart using Shopify script an undocumented feature?

john91
Tourist
8 0 1

Hi all, 

I want to use Shopify script to remove a special product from cart when a discount code is entered. The idea is that shopper cannot buy those product if discount code is used.

I found this example from Shopify documnetation. The core logic to remove a line item in this example is following

index = cart.line_items.find_index(line_item)
cart.line_items.delete_at(index)

https://help.shopify.com/en/manual/checkout-settings/script-editor/examples/line-item-scripts#limit-...

However, line_items.delete_at is a method not documented in Shopify documentation so I would like to know more before using this approach.

Is it an undocumented feature supported by Shopify? What exactly happen if I delete a line item from cart? Or is there any concern that I should aware of?

 

Additionally, if Shopiify script can be used to remove a line item. Can it also be used to limit line item quantity? There is some product that we want to limit shopper to be able to buy at most one per cart. 

I know that Shopify cart ajax can be used to modify cart content, e.g. adding / removing line item from cart. Can Shopify scritp do something similar too? Thanks!

 

 

 

 

Reply 1 (1)
PaulNewton
Shopify Partner
5189 464 1125

cart.line_items.delete_at() method takes a number(aka index) and removes an item at that position in the carts list of items.

Make small draft script and try it with a list of test items having different quantities to see.

 Or is there any concern that I should aware of?

Side effects when you remove things from a list may be other variables,methods,or classes where you've previously stored any such index number would possibly need to be rerun/updated to reflect any change in position of items in the cart.

 

For limiting items the split() method can also be used and is logic that runs right before delete_at() is used in the limit-product-quantities example script you linked:

    if line_item.quantity > num_to_remove
        split_line_item = line_item.split(take: num_to_remove)
        break

https://help.shopify.com/en/manual/checkout-settings/script-editor/shopify-scripts#split-example

 

As for adding items not available in scripts this is handled with the ajax api, and since your on ShopifyPlus you can customize the checkout to use the ajax cart api, so at certain points use that to add/update items/features in the cart.

 

Finally Combinable Discounts - EARLY ACCESS ONLY - Use Free Shipping With Other Discounts

Answers powered by coffee Buy Paul a Coffee for more answers or donate to eff.org
Problem Solved? ✔Accept and Like solutions to help future merchants
Confused? Busy? Buy a custom solution paull.newton+shopifyforum@gmail.com