Lately, I’ve been making some incremental tweaks to BrianLi.com – a static site generated with Hugo. One of the items on my list of stuff to figure out was how to display a complete word count for the whole site. All the word count-related tutorials I found online only dealt with calculating the number of words in a single post. After some trial and error, I was able to successfully generate a complete word count for all posts on my site on my archive page.
It turns out Hugo’s Scratch was what I needed. Here’s the code I’m using to generate a complete word count. This code ranges through my various post types (post, link, music, etc.) and sums the word count for each post (stored in the .WordCount
variable) together with Scratch’s .Add
method.
{{ $scratch := newScratch }}
{{ range (where .Site.RegularPages "Type" "in" (slice "blog")) }}
{{ $scratch.Add "wordcount" .WordCount }}
{{ end }}
With this code in place, the line below can be used to print the global word count.
{{ $scratch.Get "wordcount" | lang.NumFmt 0 }}
Check out my archive page if you want to see the global word count in action. If you have any questions about how to calculate a global word count for your Hugo site, feel free to send me an email or reach out to me on Twitter.