Skip to content

Instantly share code, notes, and snippets.

@radarseven
Last active January 11, 2017 16:44
Show Gist options
  • Save radarseven/3fec04b34100a58b2b01c66df56686c0 to your computer and use it in GitHub Desktop.
Save radarseven/3fec04b34100a58b2b01c66df56686c0 to your computer and use it in GitHub Desktop.
Craft 2.x - Filtering entries in a single Twig template
{# How to handle querystring filters in a single Twig template. #}
{# Baseline entries/categories criteria. #}
{# Set any criteria here that will be relevant regardless of filters. #}
{# Section name can be array if you need to fetch from more than one section. #}
{% set criteria = {
section: ['sectionName'],
order: 'postDate desc',
limit: 9
} %}
{# Check for any existing filters in the querystring. #}
{% set filters = {} %}
{# Populate with all querystring parameter to look for. #}
{% set querystringParams = ['t', 'c'] %}
{# Loop through querystring params. #}
{% for param in querystringParams %}
{# If querystring param is in the URL, merge into the filters object. #}
{% if craft.request.getParam(param) %}
{% set filters = filters|merge({
(param): craft.request.getParam(param)
}) %}
{% endif %}
{% endfor %}
{# Are we filtering? #}
{% if filters|length %}
{# Use 'and' if you want to require all relations. User 'or' to match any relation. #}
{% set relations = ['and'] %}
{# Loop through the filters and populate the relations. #}
{% for key, value in filters %}
{# Need to pass an entry ID as the `relatedTo` value. #}
{# ID as querystring value. #}
{# If using the entry ID as the querystring value, just set the id to the value. #}
{% set id = value %}
{# --------- #}
{# Slug as querystring value. #}
{# If using the entry slug as the querystring value, need to fetch the entry/category ID first. #}
{# {% set entry = craft.entries.section('sectionHandle').slug(value).first() %} #}
{# Make sure we actually have an entry, accounts for cases where the querystring may have been manipulated. #}
{#{% if entry|length %}#}
{#{% set id = entry.id %}#}
{#{% endif %}#}
{# --------- #}
{# Make sure we have an entry ID. #}
{% if id is defined and id|length %}
{% set relations = relations|merge([
{ targetElement: id }
]) %}
{% endif %}
{% endfor %}
{% endif %}
{# Merge in relations if we have any. #}
{% if relations is defined and relations|length %}
{% set criteria = criteria|merge({
relatedTo: relations
}) %}
{% endif %}
{# Finally, fetch the entries. #}
{% set entries = craft.entries(criteria) %}
<p>Criteria:</p>
<pre>{{ dump(criteria) }}</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment