Adding a Word Count to Your Theme

I searched in a few places and couldn’t find what I thought would be a pretty obvious helper functionality, similar to reading_time. So I made it myself! Here’s an example:

How to implement:

  1. On a post page, create a span where you want your word count to go:
<span class="word-count"></span>
  1. Figure out the code block in theme theme where your content shows up (in the example below, I am using .post-content as the div class where my content goes. Then, add the following code at the bottom of your post template:
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const content = document.querySelector(".post-content"); // or whatever your main content class is
    const text = content?.textContent || '';
    const wordCount = text.trim().split(/\s+/).length;
    document.querySelector(".word-count").textContent = `${wordCount.toLocaleString()} words`;
  });
</script>

It’s that easy, and I’m surprised it hasn’t already been implemented in Ghost Core. Here’s to hoping that this gets turned into a default feature similar to my last post, Creating a Custom "Announcements" Bar for your Ghost Blog (Hint hint, wink wink).

3 Likes

It would be beneficial to include this information as part of the card post data and post metadata. Users should have the option to decide whether or not they wish to display this data.