Torsten Torsten - 3 months ago 26
jQuery Question

Character limitation for WordPress WYSIWYG editor

I limited the number of characters that can be added as content for a special page (event submission page). It works fine in text or code mode in WordPress but not when I use the WYSIWYG editor.

Any idea how to change it so it also works using the WordPress editor?

Thank you so much!

Here is the JS I am using.

// Set your character limit
var count_limit = 1000;

// Set the initial symbol count on page load
$('#tcepostcontent-wc span').html($('#tcepostcontent').val());

$('#tcepostcontent').on('keyup', function () {
var char_count = $(this).val().length;
var tcepostcontent = $(this).val();
var text_remaining = count_limit - char_count;

// Update the character count on every key up
$('#tcepostcontent-wc span').html(text_remaining);

if (char_count >= count_limit) {
$('#tcepostcontent-wc').css('color', 'red');
$(this).val(tcepostcontent.substr(1, count_limit));
} else {
$('#tcepostcontent-wc').css('color', null);

}).after('<p id="tcepostcontent-wc">Max 1000 are available <span>1000</span></p>');


The visual editor of WordPress is TinyMCE and he implement a custom API there you can use to solve this topic. You should use the follow source, add it in a small custom plugin, change the id for tinyMCE.activeEditor.editorId of the editor, activate it, and done.

add_filter( 'tiny_mce_before_init', 'wpse24113_tiny_mce_before_init' );
function wpse24113_tiny_mce_before_init( $initArray ) {

    $initArray['setup'] = <<<JS
[function( ed ) {
    ed.onKeyDown.add( function( ed, e ) {
        if ( tinyMCE.activeEditor.editorId == 'content-id' ) {

            var content = tinyMCE.activeEditor.getContent();
            var max = 300;
            var len = content.length;

            if (len >= max) {
              $( '#charNum' ).html( '<span class="text-error">You've got more then '+max+' characters!</span>' );
            } else {
             var charCount = max - len;

             $( '#charNum').html( charCount + ' characters left' );


    return $initArray;

The source is from this answer in the SE Forum for WordPress topics.