I'm trying to keep a word count tally on a set of long text fields. As far as I can see, there are several options:
- Create a view and add php to a custom template that produces the word count. Most solutions I've found seem too refer back to this 2005 issue, which is considerably out of date.
This would be a viable solution, except none of the code options listed work, and I'm not savvy enough with my php or jquery to update them to D7 on my own. I've tried this:
<?php $wordcount = " | ".count(explode(" ", strip_tags(trim($content))))." words" ; ?>
But I get an invalid variable error.
- At the bottom of that same issue, there's a D6 solution that saves the word count whenever the node is saved:
function od_tweaks_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($op == "insert") { // Save the word count
$body = $node->body;
$word_count = count(explode(" ", strip_tags(trim($body))));
$nid = $node->nid;
db_query("INSERT INTO {od_tweaks} (nid, wordcount) VALUES ($nid, $word_count)");
} else if ($op == "update") {
$body = $node->body;
$word_count = count(explode(" ", strip_tags(trim($body))));
$nid = $node->nid;
db_query("UPDATE {od_tweaks} SET wordcount = $word_count WHERE nid = $nid");
}
}
- Use a module, which I would prefer to avoid. Also, most of the D7 word count modules are now obsolete. Word Count doesn't seem to do very much and there's no documentation. Field Validation requires multiple modules and a fair bit of fussing. It seems like a heavy solution for what should be a light code issue. Most of the other solutions I've found will produce a running word count for an active field, but won't save or combine.
The fields in question may be updated along with the complete node, or updated through editable fields, so I'm thinking the best way is either a hook or jquery that recounts the words every time the field is updated and then saves that value to a new field. Given my use case, this will give me flexibility to add and combine word count values in various ways.
So, it looks like option 2 is the right direction, but the code is obsolete. Is there a better way to do this in D7?