How to retrieve the total word count from all posts in WordPress

- by

Most of my own WordPress sites have been up for longer than a decade at the time of writing, and I was wondering how much I had written in that time.

Post count notwithstanding, I was interested in the total word count of my output in that period of time.

Here’s a small function that retrieves just that.

Word Count in Posts


function getWordCountFromPosts () {
$count = 0;
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => 'any'
));
foreach( $posts as $post ) {
$count += str_word_count( strip_tags( get_post_field( 'post_content', $post->ID )));
}
$num = number_format_i18n( $count );
return $num;
}

Comments

But word count from posts is not all that a website adds up to: I have answered several thousand comments since then, and my answers may fill a whole book just by itself.

Here’s how to retrieve the comment word count for the current user:


function getWordCountCommentsCurrentUser() {
$count = 0;
$user_id = get_current_user_id();
$comments = get_comments( array(
'user_id' => $user_id
));
foreach( $comments as $comment ) {
$count += str_word_count( $comment->comment_content );
}
return $count;
}

To retrieve the total word count in all comments instead, we can do much the same thing by leaving out the user_id parameter in the above query. Subtracting the total word count from the current user word count would then reveal the comment word count that everybody else has left on a site.

Both functions work outside of The Loop.

You got to love statistics 🙂



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.