[Drupal] How to get the number of words in a node?

| | 1 min read

Hey, are you the admin of your site? Do you want to get the total number of words of your node on double click? Well then, here is an article on how to get the word count of your nodes at your mouse tip in a few simple steps.

Firstly create word_count.js in your theme directory with the following contents.


// Adds Word counter for the node content
(function ($) {
  Drupal.behaviors.bodycountnode = {
    attach: function (context, settings) {
      $('.node .content .field-name-body', context).dblclick(function (event) {
        // replace(/></ig, '> <') is necessary in order to workaround block tag problems, e.g. <p>X</p><p>Y</p>.
        // Without the replace() we would get one word XY instead of X Y.
        var words = jQuery.trim(jQuery(this).html(jQuery(this).html().replace(/></ig, '> <')).text()).split(/\s+/).length;
        alert(words + " word(s)");
      });
    }
  };
})(jQuery);

Secondly place the code below, in your template.php :


function YOUR_THEME_preprocess_node(&$variables) {
  // Add a word counter for admins
  if ($variables['is_admin']) {
    drupal_add_js(path_to_theme() . '/wordcounter.js');
  }
}

Let me remind you, dont ever forget to change YOUR_THEME in the function above, to the name of your theme.

After including the above function, admin people please go to your site nodes and then double click and get the nodes word count in a message box.

Enjoy !!!