Universal Category Filters
Problem
You love the new categories in Craft 2, but need to know how to use them to filter within a section.
Solution
Start off with a default “query” to get all the “workshops”:
{% set workshops = craft.entries.section('workshops').find() %}
Then build a simple loop to show all the workshops:
{% for workshop in workshops %}
<article class="workshop" >
<h1>{{ workshop.title}}</h2>
</article>
{% endfor %}
Then show the “workshop types” categories as filter links in the sidebar, they should link to the current url with an added “category” query string variable that passes in the categories “slug”:
<ul>
{% for category in craft.categories.group('workshopTypes').find() %}
<li>
<a href="{{craft.request.url}}/?category={{ category.slug }}">{{ category.title}} </a>
</li>
{% endfor %}
</ul>
And last but not least, and an if statement around your original “query” to optionally filter by the category from the query string:
{% if craft.request.getParam('category') is not null %}
{% set category = craft.categories.slug(craft.request.getParam('category')) %}
{% set workshops = craft.entries.section('workshops').relatedTo(category).find() %}
{% else %}
{% set workshops = craft.entries.section('workshops').find() %}
{% endif %}
The Full code solution is as follows:
{% if craft.request.getParam('category') is not null %}
{% set category = craft.categories.slug(craft.request.getParam('category')) %}
{% set workshops = craft.entries.section('workshops').relatedTo(category).find() %}
{% else %}
{% set workshops = craft.entries.section('workshops').find() %}
{% endif %}
<div class="row">
<div class="col-md-8">
{% for workshop in workshops %}
<article class="workshop" >
<h1>{{ workshop.title}}</h2>
</article>
{% endfor %}
</div>
<div class="col-md-4">
<ul>
{% for category in craft.categories.group('workshopTypes').find() %}
<li>
<a href="{{craft.request.url}}/?category={{ category.slug }}">
{{ category.title}}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
Submitted by Keith Mancuso on 1st February, 2017