I want to disable input into an instance of wp_editor on the front end. This accurately tracks the number of characters, but allows input after the limit is reached.
function my_char_count( $initArray ) {
if ( ! is_admin() ) {
$initArray['setup'] = <<<JS
[function(ed) {
ed.on('keyup', function(e) {
var content = ed.getContent().replace(/(<[a-zA-Z\/][^<>]*>|\[([^\]]+)\])|(\s+)/ig,'');
var max = 20;
var len = content.length;
var diff = max - len;
if ( diff < 1 ) {
// none of these prevents input
ed.stopPropagation();
ed.preventDefault();
tinymce.dom.Event.cancel(e);
return false;
}
document.getElementById("character_count").innerHTML = "Characters Left: " + diff;
});
}][0]
JS;
}
return $initArray;
}
add_filter( 'tiny_mce_before_init', 'my_char_count' );