3

I want to create a featured story slider on my website and gather the latest entries from multiple channels to populate it.

Here is what is working:

# fetch the entries
{% set featuredBlog = craft.entries.section('blogs').limit(1).find() %}
{% set featuredArticle = craft.entries.section('articles').limit(1).find() %}
{% set featuredSpecialReport = craft.entries.section('specialReports').limit(1).find() %}
{% set featuredInfographic = craft.entries.section('infographics').limit(1).find() %}

# create a collection out of the above entries
{% set allEntries =
featuredBlog|merge(featuredArticle)|merge(featuredSpecialReport)|merge(featuredInfographic) %}

# loop over the collection and output them
{% for featuredEntry in allEntries %}
  {{ featuredEntry.title }}<br>
{% endfor %}

Now I want to sort the collection of entries by postDate so that the latest entry in the collection shows up first, no matter what section it is from. How do I do this?

I tried:

{% for featuredEntry in allEntries|group('postDate.day') %}
  {{ featuredEntry.title }}<br>
{% endfor %}

But this doesn't work and crashes the template saying Key "title" for array with keys "0, 1, 2" does not exist

So how do I sort a collection of entries from multiple sections and show them by latest date descending?

1 Answer 1

3

Rather than fetching the entries at first, just grab their IDs using ids() instead of find():

{% set featuredBlogId = craft.entries.section('blogs').limit(1).ids() %}
{% set featuredArticleId = craft.entries.section('articles').limit(1).ids() %}
{% set featuredSpecialReportId = craft.entries.section('specialReports').limit(1).ids() %}
{% set featuredInfographicId = craft.entries.section('infographics').limit(1).ids() %}

Then merge all of those arrays together:

{% set featuredIds = featuredBlogId
    |merge(featuredArticleId)
    |merge(featuredSpecialReportId)
    |merge(featuredInfographicId) %}

Once you’ve got that array of all the latest featured entries’ IDs, you can fetch their full entry models all at once:

{% set featuredEntries = craft.entries.id(featuredIds) %}

{% for entry in featuredEntries %}
    {{ entry.title }}<br>
{% endfor %}
2
  • this seems to be much more efficient but then how do I order the featuredEntries collection by date descending? I want the latest item to show up first! Nov 24, 2015 at 12:27
  • 1
    @AmitErandole Entry queries always fetch the entries in order of post date (desc) by default, but if you want to be explicit you can add .order('postDate desc') to each of the craft.entries calls. Nov 24, 2015 at 12:29

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.