1

I have a categories group named "Title" in my backend. In that group I have 15 categories, but I want to display only 3 specific categories on the frontend. How can I filter my query and display only certain categories?

{% for category in craft.categories({ group: 'title', orderBy: 'title asc' }).all() %}
    {{ category.title }} {# will display all the categories but I want to display only 3 specific categories #}
{% endfor %}

1 Answer 1

3

Your current query queries for all categories in the category group "title", ordering them by their title.

If you want to list three specific categories, you'll have to create a categories query that filters out all the other categories somehow.

In Craft, most fields can be used to filter element query results. For example, if you wanted to filter by the categories' title, you could use the .title() param – the below query would only return categories with a title "Foo", "Bar" or "Baz":

{% set categories = craft.categories.group('title').title(['Foo', 'Bar', 'Baz']).all() %}

You can also query by category IDs:

{% set categories = craft.categories.group('title').id([125, 43624, 34]).all() %}

Or even by a custom field – for example, assuming you had a Lightswitch field called featured, and wanted to query for all categories with this Lightswitch field toggled on:

{% set categories = craft.categories.group('title').featured(1).all() %}

Another approach entirely is using a Categories field, to enable authors to select which categories to display. For example, if you created a categories field called someCategoriesField, and added it to a global set someGlobalSet, you could do this to return any and all categories selected in that field:

{% set categories = someGlobalSet.someCategoriesField.all() %}

If you want to make sure that only 3 categories are returned, you might also consider adding a .limit() parameter to your query:

{% set categories = craft.categories.group('title').limit(3).all() %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.