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
This 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 TextMigration script to convert plain text to block content across your content lake
Go to Migrate plain text field to Portable TextSimple content type for a question and answer pattern
Go to Frequently asked questions