4

I'm trying to get all entries that related to one .. three categories, as determined whether their id appears in the query string:

{% set sector = craft.categories.id(craft.request.getQuery('sector')) %}
{% set impact = craft.categories.id(craft.request.getQuery('impact')) %}
{% set topic = craft.categories.id(craft.request.getQuery('topic')) %}

{% for post in craft.entries.section(section).relatedTo('and', sector, impact, topic) %}

This works well if each of sector, impact, and topic are present, but will return nothing if any one of sector, impact, topic is null (i.e. getQuery('') is blank). Can anyone suggest a way I can do this?

1 Answer 1

5

Completely untested, but try something like:

{% set ids = [] %}

{% if craft.request.getQuery('sector') %}
    {% set ids = ids|merge([craft.request.getQuery('sector')]) %}
{% endif %}

{% if craft.request.getQuery('impact') %}
    {% set ids = ids|merge([craft.request.getQuery('impact')]) %}
{% endif %}

{% if craft.request.getQuery('topic') %}
    {% set ids = ids|merge([craft.request.getQuery('topic')]) %}
{% endif %}

{% if ids|length %}

    {% for post in craft.entries.section(section).relatedTo('and', ids|join(',')) %}
        ....
    {% endfor %}

{% endif %}
6
  • Very clever solution! Is there a need for 'and' somewhere in the categories value?
    – Lindsey D
    Sep 25, 2014 at 5:11
  • Ah yes that's what I'm looking for - didn't think of the merge function. Will try that shortly.
    – Daniel
    Sep 25, 2014 at 8:49
  • Ah yes I spoke too soon: even with .relatedTo('and', categories) it performs an "or" query, rather than an "and". Any ideas?
    – Daniel
    Sep 25, 2014 at 14:03
  • Updated answer. Again... completely untested, but that should do it.
    – Brad Bell
    Sep 25, 2014 at 14:34
  • 1
    Brad, out of interest, if you've already got the ids as an array, why to you need to query them again with {% set categoriesIds = craft.categories.id(ids).ids() %} ? Sep 26, 2014 at 12:25

Your Answer

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

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