<p>I have got a list of product variants being filtered by a string of category ids if there is some data in the category parameter with the following code:</p>

<p>(Note that I'm using the + character between category IDs, which getParam converts into spaces, so I'm splitting on spaces)</p>

<pre><code>{% set categoryParams = craft.app.request.getParam('cat') %}
{% set categoryParamsArray = categoryParams|split(' ') %}

{% if categoryParams|length %}
    {% set results = craft.variants({product: product}).relatedTo(categoryParamsArray) %}
{% else %}
    {% set results = craft.variants({product: product}) %}
{% endif %}
</code></pre>

<p>This works perfectly if there is one category selected but no longer works when I select two or more. The responses are as follows:</p>

<p>✅No category selected: 22 results </p>

<p>✅One category selected: 5 results</p>

<p>❌Two categories selected: 22 results</p>

<p>Any advice on this method would be appreciated. Thanks.</p>

CC BY-SA 4.0
2019-01-03T22:11:44.277Z
You're checking for the length of `categoryParams`, but the name of the variable you're passing in is `categoryParamsArray`?
Brad Bell
CC BY-SA 4.0
2019-01-04T11:22:29.547Z
Left that bit out. Updated answer.
Jay
<category><params><filtering>
Using relatedTo with a string of category ids
# Using relatedTo with a string of category ids

(Asked by: username_0 on 2019-01-03)

I have got a list of product variants being filtered by a string of category ids if there is some data in the category parameter with the following code:
(Note that I'm using the + character between category IDs, which getParam converts into spaces, so I'm splitting on spaces)
{% set categoryParams = craft.app.request.getParam('cat') %}
{% set categoryParamsArray = categoryParams|split(' ') %}

{% if categoryParams|length %}
    {% set results = craft.variants({product: product}).relatedTo(categoryParamsArray) %}
{% else %}
    {% set results = craft.variants({product: product}) %}
{% endif %}

This works perfectly if there is one category selected but no longer works when I select two or more. The responses are as follows:
✅No category selected: 22 results 
✅One category selected: 5 results
❌Two categories selected: 22 results
Any advice on this method would be appreciated. Thanks.

**Tags:** category, params, filtering

> **Comments:**
> **username_1**: You're checking for the length of `categoryParams`, but the name of the variable you're passing in is `categoryParamsArray`?  
> **username_0**: Left that bit out. Updated answer.  

---

## 0 answers

