Querying for images by tag using GROQ in Sanity.io
Welcome to the Sanity community! Yes, you can query images by tag using GROQ with the sanity-plugin-media plugin.
According to the official documentation, tags are stored as weak references in the opt.media.tags field on asset documents. The plugin defines a media.tag document type for the tags themselves. Here's how to query images by tag:
To get all images with their associated tags:
*[_type == 'sanity.imageAsset'] {
originalFilename,
url,
"tags": opt.media.tags[]->name.current
}To filter images by a specific tag name:
*[_type == 'sanity.imageAsset' && references(*[_type == 'media.tag' && name.current == 'your-tag-name']._id)] {
originalFilename,
url,
"tags": opt.media.tags[]->name.current
}To get all images that have at least one tag:
*[_type == 'sanity.imageAsset' && count(opt.media.tags) > 0] {
originalFilename,
url,
"tags": opt.media.tags[]->name.current
}Important notes about the schema structure:
- Tags are stored in the
opt.media.tagsarray on each asset document (as weak references tomedia.tagdocuments) - Tag names use the
name.currentproperty because they're defined as slugs - The
opt.medianamespace is used because this is a third-party plugin - You use the
->operator to dereference the weak references and access tag properties
You can also query additional asset fields alongside tags:
*[_type == 'sanity.imageAsset'] {
originalFilename,
url,
altText,
description,
title,
"tags": opt.media.tags[]->name.current
}The official documentation confirms this approach in their FAQ section, where they provide an example query showing how tags are accessed via opt.media.tags[]->name.current.
You can test these queries in the Vision plugin (usually at http://localhost:3333/vision in your local studio) to explore your data structure and refine your queries based on your specific needs.
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.