This is how I query elements from multiple channels:

{% set allEntries = craft.entries.section(['publication','text', 'exhibition']).limit(null) %}

I now want to sort all these entries by a custom date field. If all channels had the same date field, I would just append order('releaseDate desc') to the query.

But as I have chosen to set up individual date fields (i.e. publicationReleaseDate, exhibitionOpeningDate) I cannot figure out how to join and sort them.

Of course I could just use the same field in all channels, but then I can't have individual field names and instructions per channel.


The order param sets the ORDER BY part of the MySQL query. You can also pass MySQL functions in it.

In your case GREATEST() should do the job:

{% set allEntries = craft.entries
    .section(['publication','text', 'exhibition'])
    .order('GREATEST(releaseDate, publicationReleaseDate, exhibitionOpeningDate) desc')
    .limit(null) %}
|improve this answer|||||
  • 2
    This totally should work, except that there’s a bug in Craft that is preventing it. Just fixed it for the next release. In the meantime, you will just need to add “field_” to the beginning of the first field handle in that GREATEST() list, e.g. GREATEST(field_releaseDate, publicationReleaseDate, exhibitionOpeningDate). (The next update won’t break that, just make it not necessary.) – Brandon Kelly Jun 12 '14 at 18:26
  • Thanks @Brandon, already noticed that bug and added "field_" to all field handles. – carlcs Jun 12 '14 at 20:55
  • As I had already merged all those date fields into one before asking this question, I can't say yet if this code is indeed working. Will do some testing tomorrow. – carlcs Jun 12 '14 at 21:01
  • By "merged" I meant that I copied the content from the separate fields into one single field, that I now use in all channels. Didn't come around to do the testing yet. Sorry for delaying the answer accept. – carlcs Jun 14 '14 at 21:42
  • 2
    @ChristianSeelbach Nope that’s not currently possible. This use case makes a good argument for it, though. – Brandon Kelly Jun 14 '14 at 21:46

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.