sanitygroq

Sanity query Filter Post by Categories


I'm new using Sanity and I'm trying to filter my sanity studio posts by category, I've been looking for answers and trying different queries, but this is the only one that has worked `

*[_type == "post" 
                                
  && defined(slug.current) 

  && (!defined($search) || title match $search || publishedAt match $search || author->name match $search) 

  && defined($category) 

  && select(defined($category) => $category in categories[]->slug.current,true) ] 
     
  | order(publishAt desc){

          title,

          publishedAt,

         "categories": coalesce(

            categories[]->{
            _id,
            slug,
            title
            },[]

         ),

        author->{

          name,

       }
   }`:

It works for one category but I want to filter by an array of categories.


Solution

  • I could find the solution:

    *[
      _type == "post" && 
      count((categories[]->slug.current)[@ in $category]) > 0
    ]
    

    This query:

    1. Selects all documents of type "post".

    2. Checks if any of the referenced categories have a slug that matches any category passed as parameter.

    3. Returns posts that have at least one matching category.

    I'll explain how the GROQ expression `count((categories[]->slug.current)[@ in $category]) ` works by breaking it down step by step:

    So, the entire expression counts how many of your post's categories have slugs that match the array passed as parameter. If the count is greater than 0, it means the post has at least one of those categories.

    This filtering technique is documented in the [Query Cheat Sheet](<https://www.sanity.io/docs/content-lake/query-cheat-sheet>), which shows examples of filtering documents based on referenced categories.