Get current post, previous post, and next post

This can be used for blogs or articles where you want to possibly display next and previous article buttons

By James Singleton & Knut Melvær


Sanity Query

*[_type == "post" && slug.current == $slug]{
  "currentPost": {
    title
  },
  "previousPost": *[_type == "post" && ^.publishedAt > publishedAt]|order(publishedAt desc)[0]{title,"slug": slug.current},
  "nextPost": *[_type == "post" && ^.publishedAt < publishedAt]|order(publishedAt asc)[0]{title,"slug": slug.current},
  "morePosts": *[_type == "post" && slug.current != $slug] | order(publishedAt desc, _updatedAt desc)[0...3] {
    ${postFields}
  }
}|order(publishedAt)[0]

Contributors

James Singleton

Senior Software Engineer at AmEx

Visit James Singleton's profile

Knut Melvær

Knut is a principal developer marketing manager at Sanity.io

Norway

Visit Knut Melvær's profile