Limit the Number of Words or Characters in WordPress Editor

Limit the number of characters or words inside WordPress post editor

Display a warning to editors when the number of characters or words exceeds a certain limit

Sometimes you want to limit the number of words that your editors or clients can enter into a post (usually of a custom post type). Here is a simple snippet of PHP and javascript that retrieves the current tinyMCE editor on the page, counts the number of characters in the editor and displays a warning if the character count exceeds a certain limit. Using a prominent warning instead of truncating content automatically offers a much better usability.

WordPress Filter and Javascript

add_action( 'admin_print_footer_scripts', 'check_textarea_length' );

function check_textarea_length() {
	?>
	<script type="text/javascript">
		jQuery( document ).ready( function($) {
			var editor_char_limit = 50;

			$('.mceStatusbar').append('<span class="word-count-message">Reduce word count!</span>');

			tinyMCE.activeEditor.onKeyUp.add( function() {
				// Strip HTML tags, WordPress shortcodes and white space
				editor_content = this.getContent().replace(/(<[a-zA-Z\/][^<>]*>|\[([^\]]+)\])|(\s+)/ig,''); 

				if ( editor_content.length > editor_char_limit ) {
					$('#content_tbl').addClass('toomanychars');
				} else {
					$('#content_tbl').removeClass('toomanychars');
				}
			});
		});
	</script>

	<style type="text/css">
		.wp_themeSkin .word-count-message { font-size:1.1em; display:none; float:right; color:#fff; font-weight:bold; margin-top:2px; }
		.wp_themeSkin .toomanychars .mceStatusbar { background:red; }
		.wp_themeSkin .toomanychars .word-count-message { display:block; }
	</style>
	<?php
}

If using this in production, remember to move both Javascript and CSS into files and use appropriate admin hooks for adding them only on pages that display the editor you need.

Make it a Plugin

It would be great if someone could turn this into a plugin where users can specify the post type, characters limit and the warning message.

9 Comments

  1. Jim says:

    I’ve actually been looking for this exact sort of plugin for a project I’m working on (and I’m having no luck finding anyone who will write one for me). I may have to play with this and see if I can tweak it to what I need.

  2. Reuben says:

    Would it be possible to adapt this to only work for a specific post type? Say “events”? Thanks!!

  3. Kaspars says:

    Sure, Reuben — simply check for the existence of the post_type query variable right at the top of check_textarea_length() function:

    if ( $_GET['post_type'] != 'name_of_your_post_type' )
    	return;
  4. Phuong says:

    Is there a way to check the existence of the post_type query for when you are on the edit screen? I tried using the code you provided for Reuben. It works for making new posts for custom post types, but not when editing existing posts.

  5. 2046 says:

    hello
    I made the plugin.
    http://2046.cz/freestuff/content-character-count-live-plugin.html

    on the way to WordPress repository.
    I changed the code slightly so it just counts the characters. But what is the major change is that it count the words right when the page is loaded, no action necessary. Your version counts it only when someone starts to type.

    Don’t wary you are mention in the code and the description as well.

  6. Paul says:

    Hi Kaspars

    I don’t know if this works with the latest version of WordPress?
    I see a javascript error
    TypeError: tinyMCE.activeEditor is null

  7. Gerald says:

    I need to do the same for the excerpt field, any hints how to modify your code?

    • Kaspars says:

      It should be much easier with the excerpt field because it doesn’t use a WYSIWYG editor. Something like this (also on JSFiddle):

      jQuery(document).ready(function ($) {
          // Set your character limit
          var count_limit = 10;
      
          // Set the initial symbol count on page load
          $('#excerpt-wc span').text($('#excerpt').val().length);
      
          $('#excerpt').on('keyup', function () {
              var char_count = $(this).val().length;
              var excerpt = $(this).val();
      
              // Update the character count on every key up
              $('#excerpt-wc span').text(char_count);
      
              if (char_count >= count_limit) {
                  $('#excerpt-wc').css('color', 'red');
                  $(this).val(excerpt.substr(0, count_limit));
              } else {
                  $('#excerpt-wc').css('color', null);
              }
      
          }).after('<p id="excerpt-wc">Count: <span>0</span></p>');
      });
  8. Mohammed says:

    Thanks a lot, It works nice.. .I made some changes to make it Limit for Title and for specific post type :) , dont forget to change Your-Post-Type-here by the post type you want.
    here is the code…

    add_action( 'admin_print_footer_scripts', 'check_title_length' );
    function check_title_length() {
      global $post_type;
      if ('Your-Post-Type-here' != $post_type) 
        return;
      ?>
      
        jQuery(document).ready(function ($) {
            // Set your character limit
            var count_limit = 70;
    
            // Set the initial symbol count on page load
            $('#title-wc span.number').text($('#title').val().length);
    
            $('#title').on('keyup', function () {
                var char_count = $(this).val().length;
                var excerpt = $(this).val();
    
                // Update the character count on every key up
                $('#title-wc span.number').text(char_count);
    
                if (char_count >= count_limit) {
                    $('#title-wc span.number').css('color', 'red');
                    $(this).val(excerpt.substr(0, count_limit));
                } else {
                    $('#title-wc span.number').css('color', '');
                }
    
            }).after('<p id="excerpt-wc">Count: <span>0</span></p>');
        });
      
      <?php
    }

Leave a Reply