Ad

Assign Products To Collection Based On Size

- 1 answer

I created a new collection template and I want to assign to it all products that have 'XL' size in their size variant.

I started from create and array of sizes for every product but now I'm stuck.

{% assign sizes = '' %}
{% for variant in product.variants %}
{% if variant.available %}
{% assign sizes = sizes | append: variant.options[0] | append: '_' %}
{% endif %}
{% endfor %}
{% assign sizesArr = sizes | split: '_' | uniq %}

What should I do next for showing only products that contains 'XL'?

Ad

Answer

It depends what do you mean by all products.

By default collection can show up to 50 products but you can overwrite this with a paginate object.

So if you have under 50 products you can just do this.

{%- for product in collection.products -%}
  {%- assign show_product = false -%}
  {%- for option in product.options_with_values -%}
    {%- for value in option.values -%}
      {%- assign value_handle = value | handle -%}
      {%- if value_handle == 'xl' -%}
        {%- assign show_product = true -%}
      {%- endif -%}
    {%- endfor -%}
  {%- endfor -%}

  {%- if show_product -%}
    Add your product here
  {%- endif -%}
{%- endfor -%}

If you have more than 50 products you will need to wrap the above code in paginate object:

{% paginate collection.products by 9999 %}
  {%- for product in collection.products -%}
    {%- assign show_product = false -%}
    {%- for option in product.options_with_values -%}
      {%- for value in option.values -%}
        {%- assign value_handle = value | handle -%}
        {%- if value_handle == 'xl' -%}
          {%- assign show_product = true -%}
        {%- endif -%}
      {%- endfor -%}
    {%- endfor -%}

    {%- if show_product -%}
      Add your product here
    {%- endif -%}
  {%- endfor -%}
{% endpaginate %}

But this request will take a toll on the server and slow down your site. So please consider this issue as well.

Ad
source: stackoverflow.com
Ad