0

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>');
Torsten
  • 91
  • 1
  • 9

1 Answers1

1

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' );
            }
         }
    });

}][0]
JS;

    return $initArray;
}

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

Community
  • 1
  • 1
bueltge
  • 2,294
  • 1
  • 29
  • 40
  • Thanks for your this however I am not sure how to use it. I have already a plugin called "Word Count and Limit" that works inside the backend for all posts and pages and also for the community event plugin but not when use this plugin in the frontend. Any idea? – Torsten Nov 23 '16 at 15:10
  • In front end, that is a sufficient difference. I don't know what you use for a editor inside the front end. If you use also the TinyMCE, than it should also work. But your plugin, maybe it checks that it only works in the admin area. – bueltge Nov 23 '16 at 15:16