Add Word Count to Single Posts in WordPress

Add Word Count to Single Posts in WordPress
This is just a quick little snippet to display a word count on the single post page in WordPress. Since it requires being placed within the loop, you can actually add it to any template file that includes a loop, such as archive.php or index.php.
The example below is for my premium Destin theme, which also has a basic version available for free through WordPress.org.
Since we’re editing the theme’s core files, I suggest first creating a child theme. This ensures that the changes stay intact when you update the theme in the future.
Check out my tutorial Creating a Child Theme in WordPress for guidance.

The Basic Function

Once you’ve created your child theme, include this short block of code in its functions.php file:

function bavotasan_word_count() {
   return sprintf(
      __( '%s words', 'text-domain' ),
      str_word_count( strip_tags( get_post_field( 'post_content', get_the_ID() ) ) )
   );
}

str_word_count is a simple PHP function that counts the number of words inside string. All we’re doing is loading up the post’s content as the string after we’ve stripped out all HTML tags. Otherwise, those tags would be counted as words and mess up the total.
With that code in place, we can add bavotasan_word_count() to the theme’s content.php file.

Displaying the Word Count

We want the word count to appear on the left with the post’s meta data, so include the new function within this block of code:


Here’s the new function:

Add it all together:


Check out the image below to see what it’ll look like:
Destin WordPress Theme with Word Count
It’s an easy enough mod that allows you to include a bit more meta data for each of your posts.
If you have any thoughts or would like to add to this tutorial, please use the comment section below.

Featured image provided by Gratisography.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie