
One of our readers, Laura, asked in the forum how to get and display the word count of a post. In fact, there is a plugin to do that, but I never heard about a code snippet. So here is a recipe to fit Laura’s needs.

One of our readers, Laura, asked in the forum how to get and display the word count of a post. In fact, there is a plugin to do that, but I never heard about a code snippet. So here is a recipe to fit Laura’s needs.
The first thing to do is to create the function. Paste the following code on your functions.php file:
function count_words($str){
$words = 0;
$str = eregi_replace(" +", " ", $str);
$array = explode(" ", $str);
for($i=0;$i < count($array);$i++)
{
if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i]))
$words++;
}
return $words;
}
Then open your single.php file and paste the following code:
Word count: <?php echo count_words($post->post_content); ?>
And word count will be displayed
18 Responses
Wouldn’t it be more resourceful to use a built in PHP function such as substr_count() to count the number of words in a string?
Using your above logic, you could simplify your function to something like:
function count_words($str){
$str = eregi_replace(' +', ' ', $str);
$words = substr_count(' ', $str) + 1;
return $words;
}
Thanks for answering my request!
However, the first one didn’t work for me, and Si’s seemed to just return ’1′ rather than the ’499′ words I know is in the post?!
Would either of these that are in my functions.php affect this?
function string_limit_words($string, $word_limit)
{
$words = explode(‘ ‘, $string, ($word_limit + 1));
if(count($words) > $word_limit)
array_pop($words);
return implode(‘ ‘, $words);
}
function get_custom_field($key, $echo = FALSE) {
global $post;
$custom_field = get_post_meta($post->ID, $key, true);
if ($echo == FALSE) return $custom_field;
echo $custom_field;
}
@Si Jobling: Very good idea! Thanks for sharing!
@Laura: Weird that it didn’t work, I tested it and it worked perfectly. Maybe you should try the hack provided by Si Jobling?
one of the lines seems to have some weird chars in it.
if (eregi(“[0-9A-Za-zÀ-ÖØ-öø-ÿ]“, $array[$i]))
The original code works great for me, too.
This shows word count for one entry. How would you show a word count for your all of your entries combined?
For all the posts it’d be a similar setup but using
$query = “SELECT post_content FROM $wpdb->posts WHERE post_status = ‘publish’
Or something similar and then running the script on that.
You could also pass the content through strip_tags(), so you won’t be counting html tags.
please the code for counting the frequency of words in a string without using the inbuilt functions
But how can you include this code into the admin panel. I would like to see wordcount while writing an article.
I have the same question as Erik, I need to see a live word count as I type
Thanks for this, I just implemented it into my site!
Trackbacks: