Laura asked: “How to get words count of your post?”

January 26, 2009 at 8:59 am

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 :)