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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 🙂