TransWikia.com

Order Entries Query by a Featured Light Switch

Craft CMS Asked by Jasen Peterson on January 29, 2021

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

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 %}

Answered by James Smith on January 29, 2021

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 %}

Answered by Marion Newlevant on January 29, 2021

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.

Answered by Jasen Peterson on January 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP