is it possible in Prismic to sort documents (e.g. blog posts) by whichever of two date fields is newer?
For example, I have:
a publish_date date field
a last_updated date field
What I want is to order results by the most recent value between these two fields per document (i.e. whichever is newer). publish_date is always filled, last_updated sometimes.
Is there a way to achieve this directly in the query? The workarounds I can think of are either not very efficient or a little annoying like adding a dedicated order_date field.
Hey Leopold, you might not need custom fields at all. The api provides first_publication_date and last_publication_date on every document and in many cases sorting by last_publication_date gives you the “most recently updated” behavior you’re after.
So you could sort by:document.last_publication_date
The limitation is that those reflects publish history, not a custom editorial rule. So for other cases, a manual order_date field would still be the fallback.
The limitation is that those reflects publish history, not a custom editorial rule. So for other cases, a manual order_date field would still be the fallback.
This is the issue. I need to be able to control those fields fully. In my case it is editorial, so last_updated doesn’t mean a typo got fixed, but rather information actually got updated in a meaningful way.
Ok I get it, so at the moment, this is not possible to do though the Prismic client queries, you can only sort by a single field, they can’t apply that kind of “per document” logic inside the query.
What you’re trying to do would require the API to, for each document, compare publish_date and last_updated, pick whichever is newer, and then sort based on that value.
So this part needs to happen on your side after fetching the data. You can:
fetch the documents
then sort them in your code by comparing those two fields for each item using your `order_date that represents the final value to sort by