'Get an array of product.id that are in the cart
I'm trying to cycle over all my product.id in my cart. I have a various product with the same product.id but different line_item.
Example:
line.item[1]: productID 2756695130141
line.item[2]: productID 2756695130141
line.item[3]: productID 2756702765085
line.item[4]: productID 2756695130141
I want to know how many different productID I have (in this case, 2). How can I do this in Liquid/Shopify?
Solution 1:[1]
Best way to do that is to use arrays. Because they have map
and unique
.
This code will return array of unique product IDs
{% assign uniqueProductIdsArray= cart.items | map: 'product_id'| uniq %}
This code will return concatenated string of unique product IDs
{% assign uniqueProductIdsString= cart.items | map: 'product_id'| uniq | join: ', ' %}
Documentation about Array filters
in liquid: https://help.shopify.com/themes/liquid/filters/array-filters
Solution 2:[2]
I think this code may help you
{% for item in cart.items %}
{{ item.id }} //This will return product id of items in cart
{% endfor %}
Please write back if this is not the solution you are looking for.
EDIT
{% assign uniqueProductIdsArray= cart.items | map: 'id'| uniq %}
Solution 3:[3]
// Best and easy solution
{% for item in cart.items %}{{item.product.id}}
{% endfor %}`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 |