javascriptphpjquerywordpresswp-editor

jQuery clone form field group add wp_editor() function to the textarea


In CPT metabox I am using wp_editor(). The first one is loading through php function. However, when I clone the form fields via jQuery, it doesn't add wp_editor but simple textarea.

So here I found a script which loads wp_editor through javascript. However, when I tried to clone/append the form fields it doesn't load the wp_editor but simple textarea.

I believe that DOM doesn't loads the wp_editor() js function. So can anyone tell me how I can load wp_editor for cloned fields?

jQuery

// Just to cross check. This is loading wp_editor on page load
jQuery('.cn-wp-editor').wp_editor();

// wp_localization
var title = cn_fields.title;
var teditor = cn_fields.editor;

// adding incremental id
var i = 1;

// clone fields
$('#add_item').on('click', function () {
    i++;
    $('#fieldgroup').append('<div class="formgroup"><div class="card-meta-box"><label for="card_title" class="card-field-label">Item Title</label><input type="text" name="' + title + '[]" id="' + title + i +'"></div><div class="card-meta-box"><textarea name="' + teditor + '[]" id="' + teditor + i +'" class="cn-wp-editor"></textarea></div><button class="remove">x</button></div><!-- formgroup -->');
    return false; //prevent form submission
});

// remove fields
$('#fieldgroup').on('click', '.remove', function () {
    $(this).parent().remove();
    return false; //prevent form submission
    i--;
});

Solution

  • You need to reinitialized wp_editor() whenever you duplicate/copy the field. Your code is not working as the copied/created field in not in DOM on page load so wp_editor() was not getting attached to those new field(s).

    Check this code:

    $('#add_item').on('click', function () {
        i++;
        $('#fieldgroup').append('<div class="formgroup"><div class="card-meta-box"><label for="card_title" class="card-field-label">Item Title</label><input type="text" name="' + title + '[]" id="' + title + i + '"></div><div class="card-meta-box"><textarea name="' + teditor + '[]" id="' + teditor + i + '" class="cn-wp-editor"></textarea></div><button class="remove">x</button></div><!-- formgroup -->');
        $('#' + title + i).wp_editor(); //<------ add this line
        return false; //prevent form submission
    });
    

    Hope this helps!