πŸ‘€ See Sanity in action: Watch product demo now β†’

return a list of posts with any unpublished drafts at the top, where if a published post has a pending draft, that takes its place instead.

1 replies
Last updated: Nov 30, 2020
This was hell to figure out, so I thought i'd share it. But basically, this returns a list of my posts, with any unpublished drafts at the top, where if a published post has a pending draft, that takes its place instead. This is to let me render my entire site in a preview mode where unpublished changes to any content take priority.

*[
  _type == "post" 
  && (
  	// either is a draft
    (_id in path("drafts.**")) ||
    // or is published and doesn't have an equivalent draft
    (
      !(_id in path("drafts.**")) &&
      (count(*[
        _type == "post"
        && (_id in path("drafts.**"))
        && (slug.current == ^.slug.current)
      ]) == 0)
    )
  )
]{
  _id,  
  title,
  slug,
  publishedAt,
} | order(select(defined(publishedAt) => 1,  0) asc, publishedAt desc)
Nov 28, 2020, 6:26 PM
Thanks for sharing, Andrew, really appreciated!
Nov 30, 2020, 12:17 PM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in