1
votes

I'm aware you can't filter collections via "OR" condition, but is there a way to pass an array of tags you want to build a collection out of? I'd like to build a giftfinder that allows the customer to select multiple options and it would show products that match ANY those tags - not products that contain ALL those tags.

I've tried doing this on an all products collection, but it only limits the results on the page you're currently on and it still seems to paginate for all the products in the collection

 {% assign tagcategories = "Animals, Sloths" | split: ',' %}
 {%- for product in collection.products -%}
      {% for tagcat in tagcategories %}
           {%- for tag in product.tags -%}
                {% if tag == tagcat %}
                     {% include 'collection-product' with collection.handle %}
                {% endif %}
           {%- endfor -%}
      {%- endfor -%}
 {%- endfor -%}

Are there any other methods or workarounds to do what I'm trying to achieve? Thanks!

1

1 Answers

0
votes

The best approach when it comes to product by tag is to use the default collection/handle/tag and request is via AJAX.

If you create a custom template only for the ajax logic so that it doesn't including the header and footer it will be easier on you.

The custom template will be something like so collection.ajax.liquid:

{% layout none %}
{%- for product in collection.products -%}
    {% include 'collection-product' with collection.handle %}
{%- endfor -%}

So in your case you will have something like so.

(async () => {
    const handels = ['animals', 'sloths'];
    for (let index = 0; index < handels.length; index++) {
        const handle = handels[index];
        const response = await fetch(`/collections/all/${handle}`).then(res => res.text());
        // do something with the response
    }
})

If you still wanted to use just liquid you can wrap your current code with a paginate tag:

{% paginate colection.products by 99999 %}
    {% assign tagcategories = "Animals, Sloths" | split: ',' %}
    {%- for product in collection.products -%}
        {% for tagcat in tagcategories %}
            {%- for tag in product.tags -%}
                    {% if tag == tagcat %}
                        {% include 'collection-product' with collection.handle %}
                    {% endif %}
            {%- endfor -%}
        {%- endfor -%}
    {%- endfor -%}
{% endpaginate %}

Please note that the liquid way will increase the load speed of the site depending on how many products you have!