I'm trying to set up a filtering system similar to the one found on the product pages on asos.com. That system has different category groups of filters, where selecting multiple filters inside a particular category group widens the results list (OR / conjuction), whereas filters across category groups narrow the results list (AND / disjunction).

I'm trying to replicate this behaviour in Craft, but I'm struggling to combine AND and OR relations. I currently do the following to build up a list of filters across category groups from a comma separated query string in the form ?regions=22,33&teams=65&sectors=42,43,44:

{% set categoryGroups = ['regions', 'teams', 'sectors', 'topics'] %}
{% set relations = ['and'] %}
{% for group in categoryGroups %}
  {% set filterValueString = craft.request.getParam(group) %}
  {% if filterValueString != '' %}
    {% set filterValues = filterValueString|split(',') %}
    {% set relations = relations|merge(filterValues) %}
  {% endif %}
{% endfor %}

{% if relations | length > 1 %}
  {% set params = params | merge({ relatedTo: relations }) %}
{% endif %}

{% set results = craft.entries(params) %}

This results in a relations array which looks like ['and', 22, 33, 42, 43, 44, 65], and creates a system where adding a filter to an already filtered category group restricts the result set further, instead of widening it to encompass the new filter. I thought perhaps that I could construct relations to look like ['and', [22, 33], [42, 43, 44], 65], and the inner arrays (category groups) would default to an OR (as it would when passing a standard array of element IDs into relatedTo), with the outer relation providing the AND, but this doesn't appear to work.

Is there anyway to get the behaviour I'm looking for?

  • Yes but I'm not sure if twig is suited for that. My hint would be: create a plugin variable and do it with php, you can create a query from your ElementCriteriaModel and include your conditions freely like you want Nov 29, 2017 at 12:19
  • Agreed, this was probably a little much for twig but I got to a solution!
    – Alex H
    Nov 29, 2017 at 12:30

1 Answer 1


I've looked at it further and arrived at a solution.

The relations array needed to be in the form ['and', {element: [22, 33]}, {element: [42, 43, 44]}, {element: 65}].

So that could be done using the following:

{% set relations = relations|merge([{element:filterValues}]) %}

Your Answer

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

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