WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I count words in a post? Something like the one displayed just below the post?

Can someone please show me the code for getting this. I have been searching everywhere.

share|improve this question
up vote 2 down vote accepted

How hard did you search? I searched Google for "wordpress count words in post" and found a function for it in the first result!

Put this in functions.php:

function prefix_wcount(){
    $content = ob_get_clean();
    return sizeof(explode(" ", $content));

Then call it in the template like this:

<?php echo prefix_wcount(); ?>
share|improve this answer
Or, better yet (albeit less known) str_word_count() – mor7ifer May 17 '12 at 16:34
@m0r7if3r php.net/str-word-count has some strange side effects with numbers and hyphens. I wouldn't use it. – toscho May 17 '12 at 16:39

Just count the spaces and add 1:

// No need to count markup.
$text        = trim( strip_tags( get_the_content() ) );
$word_number = substr_count( "$text ", ' ' );

Another way, taking the old American double space tradition into account:

$word_number = preg_match_all( '~\s+~', "$text ", $m );
share|improve this answer
I'm not sure if counting spaces is reliable. When I learned to type, it was always two spaces after the period. Long explanation as to why it's fallen out of favor here - graphicdesign.stackexchange.com/questions/2160/… – Ray Mitchell May 17 '12 at 17:20
@RayMitchell Americans … :P I have added a second approach. – toscho May 17 '12 at 17:35
@toscho - More like, Old People. – Ray Mitchell May 17 '12 at 17:58
@toscho - there's rumor that some Brits do it to, but I have a hunch they were taught by expatriates. :) – SickHippie May 17 '12 at 22:06
Also, french uses a space between the last word in the sentence and exclamation or question marks. So, yeah. Old people. :) – moraleida May 18 '12 at 13:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.