I am trying to create some kind of repeated fields and for that, I want to create a new wp editor with some unique ID.

So my question is there any way to create wp_editor using any js? same as we get using <?php wp_editor() ?> WordPress function.

I have tried using

tinyMCE .init( { mode : "exact" , elements : "accordion_icon_description_"+response.success.item_count });

but it prints very basic editor which is I think not same as of WordPress post content field editor

4 Answers
4

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 Reply

Your email address will not be published. Required fields are marked *