How to replace the content of tinyMCE editor in both text and visual mode using jQuery?

I have added a button beside the Add Media button in WordPress’ post editor. Its called Insert Content button.

When this button is pressed, it should send a content, either plain text or HTML, into the editor, replacing any text in it.

The code should work in both text and visual mode. How can I do that using jQuery?

Here is an image to further clarify the question:

enter image description here

Note: There are various answers already but they only answer replacing the text in visual mode.

1
1

The first thing to do is to select the active editor. Here we select the editor using its id, which is content.

var activeEditor = tinyMCE.get('content');

Then we use tinyMCE’s setContent:

var activeEditor = tinyMCE.get('content');
var content="HTML or plain text content here...";
activeEditor.setContent(content);

However, if the editor is in text mode to begin with, after the page has loaded, activeEditor will be null. So we need to account for that:

var activeEditor = tinyMCE.get('content');
var content="HTML or plain text content here...";
if(activeEditor!==null){
    activeEditor.setContent(content);
}

Since setContent only works for tinyMCE, this wont work if the editor is in text mode. So we have to call the textarea directly and update its value:

var activeEditor = tinyMCE.get('content');
var content="HTML or plain text content here...";
if(activeEditor!==null){
    activeEditor.setContent(content);
} else {
    $('#content').val(content);
}

However, another caveat is that if you toggled into visual mode, then toggled back into text mode, activeEditor is no longer null, so setContent will be called always instead of the textarea. So we have to check for the editor’s state.
To determine the current mode, we monitor the class of div#wp-content-wrap.
Putting it all together:

var content="HTML or plain text content here...";
if($('#wp-content-wrap').hasClass('html-active')){ // We are in text mode
    $('#content').val(content); // Update the textarea's content
} else { // We are in tinyMCE mode
    var activeEditor = tinyMCE.get('content');
    if(activeEditor!==null){ // Make sure we're not calling setContent on null
        activeEditor.setContent(content); // Update tinyMCE's content
    }
}

Leave a Comment