how would I go about setting up a route and twig template to filter by multiple tags?
Example URL scheme: example.com/tags/tag1/tag2/tag3
where tag1
, tag2
and tag3
are tags defined in a tag field inside an entry. The resulting entries list should only output entries with tag1
AND tag2
AND tag3
. tag2
and tag3
should be optional. I want to avoid the use of get params such as ?tag=tag1,tag2,tag3.
The ultimate goal is chain multiple tags to get finer results, similar to pinboard.in tag chaining.
Example:https://pinboard.in/t:javascript/t:css/t:webdev
will return entries with javascript
AND css
AND webdev
My route looks as follows
URI: tags/tag-token/tag-taken2/tag-token3
and my twig template looks like
{% set entries = craft.entries.relatedTo(tag) %}
{% if craft.request.getSegment(2) !='' %}
<h1>Entries tagged with “{{ tag.title }}”</h1>
{% if entries | length %}
<ul>
{% for entry in entries %}
<li>{{ entry.getLink() }}..</li>
{% endfor %}
</ul>
{% else %}
<p>No entries could be found with that tag.</p>
{% endif %}
{% endif %}
{% if craft.request.getSegment(3) !='' %}
{% set tag2entries = craft.entries.relatedTo('and',
{ element: entry, field: 'tags' },
{ element: entries, field: 'tags' }
) %}
{% set tag2entries = craft.entries.relatedTo(tag2-token) %}
<h1>Entries tagged with “{{ tag.title }} and {{ tag-token2}}”</h1>
{% if tag2entries | length %}
<ul>
{% for entry in tag2entries %}
<li>{{ entry.getLink() }}..</li>
{% endfor %}
</ul>
{% else %}
<p>No entries could be found with those tags.</p>
{% endif %}
{% endif %}
{% if craft.request.getSegment(4) !='' %}
{% set tag3entries = craft.entries.relatedTo(tag3-token) %}
<h1>Entries tagged with “{{ tag.title }} and {{ tag-token2}} and {{tag-token3}}”</h1>
{% if tag3entries | length %}
<ul>
{% for entry in tag3entries %}
<li>{{ entry.getLink() }}..</li>
{% endfor %}
</ul>
{% else %}
<p>No entries could be found with those tags.</p>
{% endif %}
{% endif %}
I'm am not sure how to go about using the relatedTo() function to filter entries based on those 3 tag parameters in the URL.
Any insight on how to go about this?