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.


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(); ?>
  • 2
    Or, better yet (albeit less known) str_word_count()
    – mor7ifer
    May 17 '12 at 16:34
  • 1
    @m0r7if3r php.net/str-word-count has some strange side effects with numbers and hyphens. I wouldn't use it.
    – fuxia
    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 );
  • 1
    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/… May 17 '12 at 17:20
  • 1
    @RayMitchell Americans … :P I have added a second approach.
    – fuxia
    May 17 '12 at 17:35
  • @toscho - More like, Old People. 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

Easy and straightforward approach.

$word_count = str_word_count(trim(strip_tags($post->post_content)));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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