How to create WP Editor using javascript

Thanks to Jacob Peattie’s comment I can answer this using JS only. Actually we did something similar, but prior 4.8 and it wasn’t this easy, so we did use wp_editor() in the end. But now, you can do so using wp.editor object in JavaScript. There are 3 main functions

  1. wp.editor.initialize = function( id, settings ) {

Where id is

The HTML id of the textarea that is used for the editor.
Has to be jQuery compliant. No brackets, special chars, etc.

and settings is either an object

{
    tinymce: {
        // tinymce settings
    },
    quicktags: {
        buttons: '..'
    }
}

with these TinyMCE settings. Instead of any of the 3 objects (settings itself, tinymce or quicktags) you can use true to use the defaults.

  1. wp.editor.remove = function( id ) {

Is quite self-explanatory. Remove any editor instance that was created via wp.editor.initialize.

  1. wp.editor.getContent = function( id ) {

Well, get the content of any editor created via wp.editor.initialize.


Usage could look like so

var countEditors = 0;
$(document).on('click', 'button#addEditor', function() {
    var editorId = 'editor-' + countEditors;
    // add editor in HTML as <textarea> with id editorId
    // give it class wp-editor
    wp.editor.initialize(editorId, true);
    countEditors++;
});
$(document).on('click', 'button.removeEditor', function() {
   // assuming editor is under the same parent
   var editorId = $(this).parent().find('.wp-editor');
   wp.editor.remove(editorId);
});

As the content will be automatically posted, it is not needed in this example. But you could always retrieve it via wp.editor.getContent( editorId )

Leave a Comment