0
votes

I've created a way to filter products in my Shopify shop by size on any given collection page. However, it only works when size is the only variant.

For my shop that's fine, but since I've open sourced the filter, I'd like it to work for just one variant even when there are more than one variants.

The trouble seems to be that a line like {% for variant in product.variants %} works for just one present variant (e.g. size), but I cannot seem to pass a size argument such as {% for variant in product.variants.size %}.

I even tried the recommended variant.option1 (i.e. {% for variant in product.variants.size.option %}) but to no avail.

Is there some way of outputting just an array of the size variants even when there are multiple variants for a product?

Further context.

Also, found this similar question, but it was not similar enough to provide a solution for my use case.

2
I think product.variants.size will return number of product variants total only.Minh Bui

2 Answers

2
votes
{% capture sizes %}{% endcapture %}
{% for variant in product.variants %}
    {% if variant.option1 == 'Size' %}{% capture sizes %}{{ sizes }},{{ variant.option1 }}{% endcapture %}{% endif %}
    {% if variant.option2 == 'Size' %}{% capture sizes %}{{ sizes }},{{ variant.option2 }}{% endcapture %}{% endif %}
    {% if variant.option3 == 'Size' %}{% capture sizes %}{{ sizes }},{{ variant.option3 }}{% endcapture %}{% endif %}
{% endfor %}

You can use {{ sizes }} now as a comma separated list, alternatively swap out the comma for html, for example:

{% capture sizes %}{{ sizes }}<li>{{ variant.option1 }}</li>{% endcapture %}

Then you could output the size list items as a ul using <ul>{{sizes}}</ul>.

Finally if you really did need the sizes as an array you could use split {% assign sizes_array = sizes | split: ',' }} looking at the size filter and the forloops "range" parameter may present a way to loop through that.

0
votes

the following code is much more efficient than the above by Dan Webb

{% for product_option in product.options_with_values %}
{% if product_option.name == 'Sizes' or product_option.name == 'sizes' or product_option.name == 'size' or product_option.name == 'Size' %}
        <ul>
          {% for value in product_option.values %}
          <li>{{ value }}</li>
          {% endfor %}
        </ul>
{% endif %}
{% endfor %}

first you loop through the options and check for ones with values then you check to see if the option name contains size or Size etc if so - loop through the values & output