I’m working on a Shopify project and I need some help with Liquid code. I’ve got an array with a few fruit names in it. Now I want to add all the tags from each product in the cart to this array.
Here’s what I’ve tried:
{% assign fruit_list = "bananas, grapes, cherries" | split: ", " %}
{% for product in cart.items %}
{% for product_tag in product.tags %}
{{ product_tag }}
{% assign fruit_list = fruit_list | concat: product_tag %}
{% endfor %}
{% endfor %}
<p>All fruits: {{ fruit_list }}</p>
The {{ product_tag }}
part shows up fine but the tags aren’t being added to my fruit_list
array. What am I doing wrong? How can I get all the product tags into my array?
I ran into a similar issue when working on a custom Shopify theme. The problem is that the concat
filter in Liquid expects arrays, but product_tag
is a string. Here’s how I solved it:
{% assign fruit_list = "bananas, grapes, cherries" | split: ", " %}
{% for item in cart.items %}
{% assign fruit_list = fruit_list | concat: item.product.tags %}
{% endfor %}
<p>All fruits: {{ fruit_list | join: ", " }}</p>
This approach directly concatenates the tags
array from each product to your fruit_list
. It’s more efficient as it avoids the nested loop. Also, remember to use join
when outputting the array as a string.
One caveat: this will add all tags, not just fruit names. If you need only fruit tags, you might want to filter them first based on a predefined list of fruit names.