Join our next Developer Virtual Meetup – Live Q&A, Project Showcase, Swag raffle, and more πŸ”₯

Querying categories and posts in using GROQ

7 replies
Last updated: Jun 10, 2021
Hi! First project w/ Sanity and since it seemed easiest (because it was the example in the tutorial πŸ€·β€β™€οΈ) and I thought I could modify it later I chose Blog as a template.I'm doing a site where I'm going to display different categories of handicrafts - with name/title and an image (used Post to set up this).
I've added all the different categories in Category and connected each post to the correct category.
My question is, is it possible to query on category, and how do I do that?
Jun 10, 2021, 8:42 AM
What exactly do you want to do? Do you want to get all categories and their posts? In GROQ that would be this query
*[ _type == "category"]{ ..., "posts": *[_type=="post" && references(^._id ) }
This gets every category, and for each category it gets every
that references that category. This is done using the
parent-operator ( ) and the
-function ( ).
Jun 10, 2021, 9:26 AM
I will have links to each category and when I click a specific link I want to query and see all posts for that category. For example this one:
Jun 10, 2021, 9:34 AM
Do note that this query will also include drafts unless you explicitly exclude them with
&& !(_id in path("drafts.*"))
inside the filter-component (
[ ]
). Path: In: filter:
Jun 10, 2021, 9:34 AM
In that case the first query seems like it should match. It can be extended with
*[ _type == "category" && _id == $id]{ ..., "posts": *[_type=="post" && references(^._id ) }
and you pass in the
of the category you want to find all posts for in order to only get the relevant data for that category.
A simpler version could be:

*[ _type=="post" && references($id)]
depending on if you need any information on the given category this could be extended to

*[ _type=="post" && references($id)]{..., category-> }
Jun 10, 2021, 9:38 AM
Thank you! Will try it out πŸ™ƒ
Jun 10, 2021, 9:39 AM
docs on parameters that I used:
Jun 10, 2021, 9:40 AM
Good luck πŸ˜„
Jun 10, 2021, 9:40 AM

Sanity– build remarkable experiences at scale

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

Was this answer helpful?