For information on Searchit plugin functionality overview, you can visit Searchit github page. In a nutshell, Searchit allows you to filter elements in control panel by their associated fields and attributes. In this article, we will focus on a specific use case - filtering entries by their categories, while categories are nested on multiple levels.
Filtering entries by category #
In my recent project, I was working on a website with thousands of entries, each assigned to one from over 200 categories. These categories were nested, sometimes up to 4th level. Searchit provided me and my client much-needed functionality - filtering through these entries by their categories. However, after some time I noticed that there are some limitations. This is a filter config I have came up with initially:
{% set handle = 'category_handle' %}
{% for category in craft.categories.group(handle).all() %}
{{ ({
filter: {
relatedTo: category.id
},
label: category.title
})|json_encode() }}{{ not loop.last ? â,â }}
{% endfor %}
Notice that Searchit uses Twig for its filter configs - thanks to that we have quite large flexibility in how we want our data filtered. But in the end, filtering is done just by using html <select>
field, so there are some limitations. In that case: all categories, regardless of their nesting depth were displayed one after another and nothing distinguished level 1 category from level 4.
Solution - simulating "tree view" #
To make category list inside <select>
more readable, I decided to prepend =
characters to category title - the more nested category was, the more equal signs would be appended. Using twig, This was done quite easily.
{% set handle = 'category_handle' %}
{% for category in craft.categories.group(handle).all() %}
{% set line = '' %}
{% set depth = category.getAncestors()|length %}
{% for number in range(0, depth) %}
{% set line = line ~ '=' %}
{% endfor %}
{{ ({
filter: {
relatedTo: category.id
},
label: line ~ ' ' ~ category.title
})|json_encode() }}{{ not loop.last ? ',' }}
{% endfor %}
There is one slight drawback worth mentioning. If your website has multiple pages, categories names will always be displayed in language of first page, even if we switch language to other on entries list. If you want these categories displayed in other language, just adjust category query in second line.
How does it looks like in practice? #
In example below we can see nested list of "places" categories - composed of continents, countries and cities: