That and
argument only applies to the other top-level relatedTo arguments. If one of those arguments targets multiple elements (e.g. categories
), those will still be glued together with “OR”.
You would need to set it up like this instead:
{% set resources = craft.entries.section('resources').relatedTo(
'and',
{ targetElement: category1 },
{ targetElement: category2 }
) %}
If you don’t know all of the categories ahead of time, you can create the parameter value dynamically like this:
{# Get the category IDs #}
{% set catIds = craft.categories[...].ids() %}
{# Create the relatedTo param value #}
{% set relatedTo = ['and'] %}
{% for id in catIds %}
{% set relatedTo = relatedTo|merge([id]) %}
{% endfor %}
{# Now find our entries #}
{% set resources = craft.entries.section('resources').relatedTo(relatedTo) %}
Update
This is significantly easier in Craft 2.5 (currently in beta), as the relatedTo param’s element
, targetElement
, and sourceElement
sub-properties can now begin with 'and'
, which tells Craft to only return elements that are related to all of the following element IDs.
Here’s a quick example:
{# Start with a list of category IDs that must be included #}
{% set catIds = [1, 2] %}
{# Find the entries #}
{% set resources = craft.entries({
section: 'resources',
relatedTo: {
targetElement: ['and']|merge(catIds),
}
}) %}