Knut Melvær
Knut is a principal developer marketing manager at Sanity.io
Make a rough calculation of word count and reading time for your Portable Text fields
*[
_type == "post"
]{
title,
"numberOfCharacters": length(pt::text(body)),
// assumes 5 characters as mean word length
// https://ux.stackexchange.com/questions/22520/how-long-does-it-take-to-read-x-number-of-characters
"estimatedWordCount": round(length(pt::text(body)) / 5),
// Words per minute: 180
"estimatedReadingTime": round(length(pt::text(body)) / 5 / 180 )
}
{
"wpm": 180,
"meanWordCharacterCount": 5
}
{
"posts": *[_type == "post"]
{
...,
"numberOfCharacters": length(pt::text(body))
}
{
title,
"estimatedWordCount": round(numberOfCharacters / ^.^.meanWordCharacterCount),
"estimatedReadingTime": round(numberOfCharacters / ^.^.meanWordCharacterCount / ^.^.wpm)
}
}
It's possible to estimate word count and reading time for Portable Text fields using GROQ. You need to make some assumptions about the mean character count for words, and words per minute. Because pt::text()
currently only supports top-level block fields, custom blocks aren't included in this estimation.
You can also do a trick where you chain projections in order to set the constants at the top of the query to reuse them. Remember to use the parent hat operator (^
).
The algorithm is borrowed from this discussion on Stack Exchange.
Knut is a principal developer marketing manager at Sanity.io
Automatically track when content was first published with a timestamp that sets once and never overwrites, providing reliable publication history for analytics and editorial workflows.
Go to First Published Timestamp FunctionAI-powered automatic tagging for Sanity blog posts that analyzes content to generate 3 relevant tags, maintaining consistency by reusing existing tags from your content library.
Go to Auto-Tag FunctionThis can be used for blogs or articles where you want to possibly display next and previous article buttons
Go to Get current post, previous post, and next postHow to automatically generate linked headings with a custom serializer
Go to Anchored Headings for Portable Text