user3571889 user3571889 - 3 years ago 110
jQuery Question

How Count Chracters in WordPress Visual Editor

For Development purpose, I need to know total number of Characters user has typed.

WordPress uses TinyMCE, Using the logic below, I am able to get character count in console if I edit using Text Editor. But it doesn't work for Visual Editor. WHy ? How to count characters typed in Visual Editor ?

jQuery(function ($) {
$("html").load().on("keyup", function () {
var content = document.getElementById("content").value.length;

Answer Source

I don't know what the main purpose of your to count character like that from TinyMCE anyway normal admin script file won't work for this. because you have to need tinymce plugin variable to do something with it.

So first add this code to your functions.php to initialize tinymce plugins filter.

function tinymce_init() {
    // Hook to tinymce plugins filter
    add_filter( 'mce_external_plugins', 'tinymce_plugin' );
add_filter('init', 'tinymce_init');

function tinymce_plugin($init) {
    // We create a new plugin... linked to a js file.
    // Mine was created from a plugin... but you can change this to link to a file in your plugin
    $init['my_event'] = get_template_directory_uri() . '/js/myscript.js';
    return $init;

Then add get content length from the wp_editor after keyup event. Just add on myscript.js

jQuery(document).ready(function($) {
    // Create 'keyup_event' tinymce plugin
    tinymce.PluginManager.add('my_event', function(editor, url) {
        // Create keyup event
        editor.on('keyup', function(e) {
            var theContent = tinyMCE.activeEditor.getContent();
            // alert( theContent.length );
            console.log( theContent.length );

Hope it make sense to you!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download