How to display a wordcount for Drupal nodes

[Note: I don't use a wordcount on the site nowadays, and this hint was for a previous version of Drupal, 4.x IIRC.]

If you are viewing the site in a browser rather than an aggregator, you'll notice a wordcount displayed in the service links at the bottom of posts. There was a thread on drupal.org covering how to accomplish that sort of thing, but there were a couple of issues with the method. Here is my solution (also posted on the thread) in case anybody else is interested:

In themes/foobar/node.tpl.php (where foobar is the name of your chosen Drupal theme), add this on a single line:

<?php $wordcount = " | ".count(explode(" ", strip_tags(trim($content))))." words" ; ?>

I added it on a new line just after line 4, which has "}?>" in my version of the file. Then, make the following changes to the line that starts with "<?php if ($links)"

<?php if ($links) { ?> <div class="links">&raquo; <?php print $links; print $wordcount ?><?php }; ?>

One caveat -- if you have any modules activated that add stuff to the $content block (e.g. the nodevote module), it will throw off the count.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Allowed HTML tags: <a> <cite> <code> <strong> <em> <blockquote> <b> <i> <p> <br> <ul> <ol> <li> <small>
  • Lines and paragraphs break automatically.

More information about formatting options