Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to fetch tags from Sanity and count their usage in posts for front-end display

4 replies
Last updated: Jun 4, 2023
I'm trying to get all of my tags from Sanity but also count how many posts use it so I can know if I need to display the tag on the front-end or not. Currently using:

'tags': *[_type == "tag"] | order(title asc){
      title,
      slug,
      _id,
      "references": *[count((_type == "post" && tags[]->slug.current)[@ == <The current tag's slug>]) > 0]
    }
As you can see, I'm struggling with how to reference the current tag's slug in the query.

The desired outcome is that I only fetch tags that have been used by other content, so I'm not fetching un-needed data or displaying a tag with no content on the front-end.
Jun 3, 2023, 6:39 PM
You should be able to access the current slug using:
^.slug.current
Jun 3, 2023, 7:10 PM
Thanks! Still not working and only returning an empty array, but I'll work it out. Cheers for the response
Jun 3, 2023, 7:46 PM
I think you may be complicating the references projection, since you need to compare a single slug to and array of slugs. Can you try:
*[_type == "post" && ^.slug.current in tags[]->slug.current]

Jun 3, 2023, 10:38 PM
This is awesome. Thanks
Jun 4, 2023, 11:07 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?