🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Get related items of a post in sanity by comparing category array reference with another array

By Alexander Staubo & Surjith S M

Suppose you have an Array Reference to Category and you want to get all posts with one of the categories listed in the current post. This is usually when you need to get related items.


*[_type == "post" && slug.current == $slug][0] {
  "related": *[_type == "post" && count(categories[@._ref in ^.^.categories[]._ref]) > 0] | order(publishedAt desc, _createdAt desc) [0..5] {

// Params
// {"slug": "my-post"}

The above code will fetch all posts if one of the categories in the post matches with the current post's category array. This is mainly achived using the @ Operator.

count(categories[@._ref in ^.^.categories[]._ref]) > 0

This will give you true if any element in categories is also in the post’s category list. If you want all to match exactly, you have to compare == count(categories).


Use foo._ref instead of foo->_id, as it’s much faster to not join unless you need what's inside.


Other schemas by authors