1

This works for filtering by tag array

{% set relatedToParam = ['or'] %}

{% for id in selectedTagIds %}
    {% set relatedToParam = relatedToParam|merge([{
        targetElement: id
    }]) %}
{% endfor %}

{% set entries = craft.entries.relatedTo(relatedToParam) %}

But how can we add another relatedTo param for category so the results only show the selected tag entries from a category?

For example to achieve this:

...WHERE categoryid = 'myid' AND (tag1 LIKE 'green' OR tag2 LIKE 'red' OR tag3 LIKE 'yellow' etc)
2

The relatedTo function accepts multiple different formats. If you want to search for Elements that are related to a list of categories and a list of tags you can do that like this

relatedTo([
    'and',
    ['element' => [1, 2, 3]],
    ['element' => [4, 5, 6]]
]);

This will return you all Elements that are related to the first array and related to the second array. So you goal should be to create an array of category IDs and Tag IDs and pass them together in the relatedTo

To get Elements that are related to all elements of one array and a single one from another array do the following

relatedTo([
    'and',
    ['element' => [1, 2, 3]],
    ['element' => ['and', 4, 5, 6]]
]);
4
  • Thank you for this it has helped, although I haven't yet managed to succeed with the second example. I have in any case used something similar to the first example you give, but using 'or' for our tags array and then filtered the result to only show entries in the categories we need.
    – Martin
    Feb 20 '19 at 15:07
  • The Code itself works, I tested and used it many times so without knowing your exact issue there is nothing I can really do. Furthermore it's a little bit difficult what you really want. What does not work exactly? Feb 20 '19 at 15:19
  • Sorry I am sure your code does work. We are just not sure how to recreate your second example in our template This is what we have working at present: {% set relatedToParam = ['or'] %} {% for id in selectedTagIds %} {% set relatedToParam = relatedToParam|merge([{ targetElement: id }]) %} {% endfor %} Using relatedTo(relatedToParam) we get entries that match ANY of the tags Then within the results we only want to show matched tags from a particular category
    – Martin
    Feb 20 '19 at 16:22
  • So you only want to match tags that are related with a particular category? By the way: creating such nested arrays in Twig is a real pain. It's easier with PHP Feb 20 '19 at 16:57

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.