How to add a character count to Wysiwyg fields

Created by Phil Kurth, Modified on Sun, 25 Sep, 2022 at 1:58 PM by Phil Kurth

This example uses the snippet found here and implements a count at the bottom of the Wysiwyg field as per the following screenshot:

To implement this, simply past the following snippet into your functions.php file, a template file, or a custom plugin and set the `characterLimit` JS variable to the desired limit.


<?php

add_action( 'af/form/after_fields', function () {
  ?>
  <script type="text/javascript">
    jQuery(function () {
      acf.addFilter('wysiwyg_tinymce_settings', function (mceInit) {
        mceInit.elementpath = false;
        mceInit.setup = function (ed) {
          var characterLimit = 1000, // todo - set desired character count here
            edContainer,
            countChar,
            colorOriginal;

          ed.on('init', function (e) {
            edContainer = jQuery(ed.iframeElement).closest('.acf-input');
            countChar = edContainer.find('.mce-statusbar .mce-flow-layout')
              .prepend('<div class="mce-path mce-flow-layout-item mce-first count-char"><span class="count-char-current">0</span><span>/' + characterLimit + '</span></div>')
              .find('.count-char-current');
            colorOriginal = countChar.css('color');
          });

          var limit = function (e) {

            var node = ed.getBody(),
              text = (node.innerText || node.textContent),
              textTrim = text.trim(),
              length = (textTrim.length === 0) ? 0 : text.length;

            if (length > characterLimit) {
              countChar.css('color', 'red');
            } else {
              countChar.css('color', colorOriginal);
            }

            countChar.text(length);
          };

          ed.on('change', limit);
          ed.on('keyup', limit);
        };
        return mceInit;
      });

    });
  </script>
  <?php
} );

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article