Show the word count of your body in a node preview

Estimated reading time of this article: 1 minute 27 seconds

Do you know how many words your article have?

If you want to show the word count of your body field in Drupal 7, then you can put the following code in a module:

<?php
/**
 * Implements hook_theme_registry_alter().
 * Replaces theme_node_preview with theme_YOUR_THEME_node_preview.
 */
function YOUR_MODULE_theme_registry_alter(&$theme_registry) {
  if (isset(
$theme_registry['node_preview'])) {
   
$theme_registry['node_preview']['function'] = 'theme_YOUR_MODULE_node_preview';
  }
}

/**
 * Returns HTML for a node preview for display during node creation and editing.
 *
 * @param $variables
 *   An associative array containing:
 *   - node: The node object which is being previewed.
 *
 * @ingroup themeable
 */
function theme_YOUR_MODULE_node_preview($variables) {
 
$node = $variables['node'];
 
// call original theme function
 
$output = theme_node_preview($variables);
 
$count = isset($node->body[$node->language][0]) ? YOUR_MODULE_count_words_in_html($node->body[$node->language][0]['value']) : 0;
 
$output .= '<h3>Word count</h3>';
 
$output .= '<div>' . format_plural($count, '1 word', '@count words') . '</h3>';

  return
$output;
}

/*
 * Count words in HTML text.
 * Helper function.
 */
function YOUR_MODULE_count_words_in_html($str = '') {
 
// str_replace('><', '> <' is necessary in order to workaround block tag problems, e.g. <p>X</p><p>Y</p>.
  // Without the str_replace we would get one word XY instead of X Y.
  // Convert non-breaking space to space. The non-breaking space is added, e.g by the module Typography in order to avoid orphan words.
 
return preg_match_all("/\S+/", preg_replace('/(' . chr(160) .'|&nbsp;)/', ' ', strip_tags(str_replace('><', '> <', trim($str)))), $matches);
}
?>