Count images in array of content blocks with GROQ
Yes! There's actually a pretty straightforward way to count images across different content blocks using count() and math::sum() in GROQ.
Here's the basic approach:
*[_type == "article"] {
title,
"imageCount": count(content[_type == "image"])
+ coalesce(math::sum(content[_type == "gallery"].images[].count(*)), 0)
+ coalesce(math::sum(content[]{count(images)}), 0)
}But the exact query depends on your schema. Here's a more flexible pattern that handles multiple block types with images:
*[_type == "article"] {
title,
"imageCount":
// Count standalone image blocks
count(content[_type == "imageBlock"])
// Add images from gallery blocks
+ math::sum(
content[_type in ["imageGalleryBlock", "inlineImagesBlock"]] {
"count": count(images)
}.count
)
}The key is:
- Use
count()for simple arrays of image blocks - Use
math::sum()combined withcount()when you have nested arrays (like galleries) - Filter by
_typeto target specific block types
If you want to get fancy and combine it with your word count for the teaser:
*[_type == "article"] {
title,
"readTime": round(length(pt::text(content)) / 200),
"imageCount": count(content[_type == "imageBlock"])
+ math::sum(content[_type == "gallery"]{count(images)}.count)
}Then in your frontend you can format it as "12 minute read and 43 images".
The GROQ count() function documentation has more details, and there's a helpful community answer that covers this exact use case with portable text content!
Show original thread2 replies
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.