1

I have a case studies filter that allows you to filter case studies by category. I've attached a light switch field called 'featured' to the entries that allow you to set it as featured. The idea is to have featured case studies appear first when filter results are returned. I've seen a few post discussing using an innerJoin to do this but I'm not sure if that's the right path or not. Any help would be greatly appreciated.

3 Answers 3

1

You're looking for the filter filter. Here's how you might do it:

{% set entriesInCat = craft.entries.relatedTo(category).all() %}
{% set featuredEntriesInCat = entriesInCat|filter(entry => entry.yourLightswitchFieldHandle) %}
{% set remainder = entriesInCat|without(featuredEntriesInCat) %}

{% for item in featuredEntriesInCat %}
    <h2>{{ item.title }}</h2>
{% endfor %}

<hr>

{% for item in remainder %}
    <h2>{{ item.title }}</h2>
{% endfor %}
1

You can add an orderBy clause to the query, and order by the lightswitch field. For example, to fetch all the entries in section things, with the ones with the featured lightswitch turned on first, do this:

  {% set things = craft.entries({
    section: 'things',
    orderBy: 'featured desc'
  }).all %}
1

To anyone else that needs to something similar:

{% set query = {
  section: 'case_studies',
  limit: entry_limit,
  orderBy: 'featured desc, postDate desc',
}%}

The pagination is wonky without the secondary orderBy parameter. I'm guessing it's because the field for an inactive lightswitch is empty in the DB? I'm speculating, but prior to adding that it would just show the same projects over and over again.

I appreciate all who answered.

1
  • I'm implementing a very similar feature, but on a "structure" data set. I can't figure out what the second parameter would be instead of postDate to get the structure's ordering… Any idea? Thanks!
    – Yann
    Jul 25, 2022 at 21:33

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.