I need to filter a sections entries by more than one category but only return entries that belong to all category id's passed in a URL parameter.

Now I can get the correct output if the id's are hard coded but not if contained in the URL parameter.

URL: ajax-swatches?cats=171,172,179

{% set catPars = craft.request.getParam('cats') %}

{% set swatches = craft.entries({ section: 'swatches', relatedTo: ['and',catPars] }) %}

I presume the 'relatedTo' section is treating the 'catPars' variable as a single entry and ignoring the ',' and next values?

Any help would be really appreciated :)

1 Answer 1


Craft's relatedTo takes a model, an ID, or an array of either of these. So if you're passing '171,172,179' It's probably coming through as a string and only reading the first ID.

Try making it an array and looping through the values:

{% set catPars = craft.request.getParam('cats')|split(',') %}
{% set related = ['and'] %}
{% for catPar in catPars %}
    {% set related = related|merge([{targetElement: catPar}]) %}
{% endfor %}

{% set swatches = craft.entries({ section: 'swatches', relatedTo: related }) %}

Without knowing your setup I don't know if it's actually targetElement or sourceElement. You can also pass in the field name as well if you want to get more specific. See the documentation linked above for the definitions of all of those.

  • Hi Peter, thank you for the reply. I have tried a range of methods using the guidelines but none seem to help. When I try your method I get no entries at all :( Commented Apr 14, 2015 at 13:51
  • You're right, that was incorrect -- I updated it with a better answer.
    – Peter Tell
    Commented Apr 14, 2015 at 14:10
  • Hi Peter, I actually used your first answer to do exactly this. However 'catPar' fails to add to the array so we end up with one array entry of 'and'.... Commented Apr 14, 2015 at 14:17
  • Can you edit your original question and post your code? I've tested that exact code and it works fine for me.
    – Peter Tell
    Commented Apr 14, 2015 at 14:19
  • It could be that you need extra square brackets around the hash to merge, so it's merge([{ targetElement: catPar }]).
    – carlcs
    Commented Apr 14, 2015 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.