Multiple section query with section wise ordering in Craft CMS

167 views Asked by At

I have multiple 2 sections named 'Events' and 'Latest News' in Craft CMS. I post entries with date in these sections. My problem is I have slick carousel in front end, where I want to display entries from both of these sections, but ordered by date. Like events should be ordered by event date and latest news should be ordered by news date. How can we achieve this in single query using Craft CMS twig template.

{% set entries = craft.entries.section(['events', 'latestNews']) %}

The above query gives me all the entries from events and latest news section. But, I don't know how to order them with section wise fields in a single query.

1

There are 1 answers

0
MoritzLost On

All entries have a post date by default, and you can order queries by that post date, even if you're querying across multiple sections:

{% set entries = craft.entries()
    .section(['events', 'latestNews'])
    .orderBy('postDate DESC')
    .all()
%}

This will return all entries in both sections, ordered by the post date in descending order.


If you are using two different fields for news date and event date, that's a bit more involved. You could use a database expression, but that's pretty complicated and not good for performance.

In this case, I would use a Preparse field set to a date value. In the template, output the news date or the event date based on the section the entry is in. Then order by the Preparse field. Check the examples in the plugin documentation for how to output date values in Preparse fields.