GROQ query to filter blog posts by category slug
Hey there! I can help you with that. To filter blog posts by a category with a specific slug, you need to use the reference access operator (->) in your GROQ query to dereference the category reference and access its slug field.
Here's the query you need:
*[_type == "post" && category->slug.current == "content-marketing"]Let me break this down:
*[_type == "post"...]- Filters all documents of type "post" (adjust "post" to match your blog post document type)category->- The reference access operator dereferences your category reference to access the actual category documentslug.current == "content-marketing"- Accesses the slug field (typically stored asslug.currentin Sanity) and checks if it equals "content-marketing"
If you want to include the full category data in your results, you can add a projection:
*[_type == "post" && category->slug.current == "content-marketing"] {
_id,
title,
category->,
// other fields you need
}Common issues to watch out for:
- Make sure your document type name matches (might be "blogPost" or "article" instead of "post")
- The slug field is usually
slug.current, not justslug - If the category field is an array of references, use
"content-marketing" in category[]->slug.currentinstead
You can test this query in Sanity Vision (the Vision plugin in your Studio) to make sure it returns the right results before using it in your code.
Let me know if you're still having issues and I can help you troubleshoot further!
Show original thread18 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.