4

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.

3 Answers 3

7

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(){
    ob_start();
    the_content();
    $content = ob_get_clean();
    return sizeof(explode(" ", $content));
}

Then call it in the template like this:

<?php echo prefix_wcount(); ?>
2
  • 2
    Or, better yet (albeit less known) str_word_count()
    – mor7ifer
    Commented May 17, 2012 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
    Commented May 17, 2012 at 16:39
6

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 );
5
  • 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/… Commented May 17, 2012 at 17:20
  • 1
    @RayMitchell Americans … :P I have added a second approach.
    – fuxia
    Commented May 17, 2012 at 17:35
  • @toscho - More like, Old People. Commented May 17, 2012 at 17:58
  • @toscho - there's rumor that some Brits do it to, but I have a hunch they were taught by expatriates. :)
    – SickHippie
    Commented May 17, 2012 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
    Commented May 18, 2012 at 13:50
6

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 and acknowledge you have read our privacy policy.

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