Add Word Count to Single Posts in WordPress
by Bandicoot Marketing on | Posted in Tutorials | 4 comments
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:
<div class="col-md-3 entry-meta"> <p><i class="fa fa-bookmark"></i> <?php _e( 'Posted in ', 'destin' ); the_category( ', ' ); ?></p> <?php if ( comments_open() ) { ?> <p><i class="fa fa-comments"></i> <?php comments_popup_link( __( '0 Comments', 'destin' ), __( '1 Comment', 'destin' ), __( '% Comments', 'destin' ), '', '' ); ?></p> <?php } ?> </div>
Here’s the new function:
<p><?php echo bavotasan_word_count(); ?></p>
Add it all together:
<div class="col-md-3 entry-meta"> <p><i class="fa fa-bookmark"></i> <?php _e( 'Posted in ', 'destin' ); the_category( ', ' ); ?></p> <p><?php echo bavotasan_word_count(); ?></p> <?php if ( comments_open() ) { ?> <p><i class="fa fa-comments"></i> <?php comments_popup_link( __( '0 Comments', 'destin' ), __( '1 Comment', 'destin' ), __( '% Comments', 'destin' ), '', '' ); ?></p> <?php } ?> </div>
Check out the image below to see what it’ll look like:
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.
4 comments for “Add Word Count to Single Posts in WordPress”