👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Get current, previous and next post, filtered by tags

By Remi Sture & Peter

This snippet can be used to fetch current, previous and next articles based on publication date and related tags.

GROQ

*[_type == $type && slug.current == $slug]{
    "current": { 
      "slug": slug.current, title, publicReleaseDate, "tags": tags[]->tag 
    },
    "previous": *[_type == $type && count((tags[]->tag)[@ in ^.^.tags[]->tag]) > 0 && ^.publicReleaseDate > publicReleaseDate]|order(publicReleaseDate desc)[0]{ 
        "slug": slug.current, title, publicReleaseDate, "tags": tags[]->tag
    },
    "next": *[_type == $type && count((tags[]->tag)[@ in ^.^.tags[]->tag]) > 0 && ^.publicReleaseDate < publicReleaseDate]|order(publicReleaseDate asc)[0]{ 
        "slug": slug.current, title, publicReleaseDate, "tags": tags[]->tag
    },
}|order(publicReleaseDate)[0]

Params

{
  type: "news_article",
  slug: "my-article-slug",
}

Example result

{
    "current": {
      "slug": "current-article",
      "title": "Current article"
      "publicReleaseDate": "2022-09-22",
      "tags": ["news"],
    },
    "next": {
      "slug": "next-article",
      "title": "Next article"
      "publicReleaseDate": "2022-10-11",
      "tags": ["news"],
    },
    "previous": {
      "slug": "previous-article",
      "title": "Previous article"
      "publicReleaseDate": "2022-08-31",
      "tags": ["news"],
    }
}

Inspired by this snippet by Knut Melvær.

Contributors

Other schemas by authors

Matching the end of a string in GROQ

GROQ doesn't yet include a function to match the end of a string, but we can simulate it by splitting our string on our term.

Geoff Ball
Go to Matching the end of a string in GROQ