Surjith S M
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
A short snippet to filter category, tags or other document based on total referenced count.
*[_type == "category"] {
...,
"count": count(*[_type == "post" && references(^._id)])
} | order(count desc) [0...10]
This snippet first get the data from category and then fetches count based on references(^._id)
and finally sort desc based on the count.
See:
https://www.sanity.io/docs/groq-functions#5759ed6ff047
https://www.sanity.io/docs/query-cheat-sheet#1ca403b172cb
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
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.
Go to Get related items of a post in sanity by comparing category array reference with another arraySnippet for `internalLInk` Reference in GROQ and rendering it in React/Next.js frontend using Portabletext.
Go to Sanity internalLink render in React with Portable TextSanity preview component cannot access the parent/document if its inside an array or object. Using Custom Preview component, we can solve the issue.
Go to Sanity Custom Preview Component to get Parent DocumentSanity provides various custom functions inside the schema. But getting a reference field value is difficult. Here's the how I do it using fetch.
Go to Get Sanity Reference Field Values inside Custom Schema Functions