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

Blog Posts - How to Sort and Filter by Category in Next.js?

4 replies
Last updated: Dec 14, 2021
So I've managed to get my blog posts and data from Studio into my NextJS blog. I've created various categories for blog posts and would like to allow my users to both sort and filter by category. Hiwev, I'm stumped as to how! The blog page has a nice list of categories (Basics, How to, Book, etc.) I'd like users to be able to click, say, "Basics" and only see those posts. I've tried searching for tutorials and guidance but am coming up short.
Any tips or links to some how-to's that I can follow?

Thanks!
Dec 12, 2021, 4:44 PM
Hey Rich! How are you indicating which category a blog post belongs to? Is it referencing a category document?
Dec 13, 2021, 6:14 PM
Yes, it's referencing a category document. I have a (small for now) set of categories and select one or more within each post, referencing the category document.
Dec 14, 2021, 8:13 PM
Got it. Here's an example of checking for other posts that reference the same category of the current post:
*[_type == 'post']{
  ...,
  'relatedPosts': *[_type == 'post' && ^.category._ref match category._ref]
}
Dec 14, 2021, 8:43 PM
Thanks,
user M
. I probably won't get to this today but I'll try it out tomorrow. Appreciate the help.
Dec 14, 2021, 9:45 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