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.

  • You're checking for the length of categoryParams, but the name of the variable you're passing in is categoryParamsArray?
    – Brad Bell
    Jan 3 '19 at 22:11
  • Left that bit out. Updated answer.
    – Jay
    Jan 4 '19 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.