8

How do I filter a list of entries by the value of a field? For example, if I have a lightswitch field called "Featured", how do I output just the featured entries?

11

Filtering a list of entries is quite simple. Here's an example from one of our sites:

{% for job in craft.entries({
    section: 'jobs',
    applicationsClose: ">= " ~ (now|date('Y-m-d')),
    internalExternal: 'external',
}) %}

    ...

{% endfor %}

Here we define the section we're looking in and then filter by two custom fields: applicationsClose and internalExternal.

1
  • Should be the better answer since there is no searching involved.
    – biko
    May 8 '20 at 8:50
8

Use the search parameter in the craft.entries model:

{% for entry in craft.entries.section('Blog').search('featuredFieldName:1') %}

    {# Entry Code #}

{% endfor %}

To filter by a specific text snippet:

{% for entry in craft.entries.section('Blog').search('entryColor:"green"') %}

    {# Entry Code #}

{% endfor %}

You can create more complex search queries as well, see the documentation for more info. But the basic idea is to use .search(), then enter your search query in quotes.

1
  • While the search query param will work for many field values, it ultimately gets parsed back into an explicit ElementQuery. The recommended way to filter by custom field data (or built-in Element properties) is to use the chaining syntax demonstrated in other answers; in addition to allowing for a wider variety of filtering strategies, it tends to be much easier to distinguish syntax issues (Twig and Search) from search index issues. Sep 14 at 21:58
5
{% set featuredProducts = craft.entries
    .section('sectionName')
    .featured(true)
    .all() %}

Where sectionName is the name of your section;

featured is your featured field handle;

true is the value you want to query the lightswitch fields for.

Each field type in the Craft docs has an element query example, e.g. lightswitch fields

3

Another way for Craft 3

{# Create an entry query with the 'section' and 'limit' parameters #}
{% set entryQuery = craft.entries()
    .section('Blog')
    .search('entryColor:green')
    .limit(10) %}
                
{# Fetch the entries. #}
{% set entries = entryQuery.all() %}

{% if entries|length > 0 %}
    {% for entry in entries %}
        {{ entry.title }}
    {% endfor %}
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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