Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

2 Answers 2

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

Then call it in the template like this:

<?php echo prefix_wcount(); ?>
share|improve this answer
1  
Or, better yet (albeit less known) str_word_count() –  m0r7if3r 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. –  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
    
thanks toscho... that worked. :) –  Ronny May 17 '12 at 16:39
    
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

Your Answer

 
discard

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.