Loading wp_editor via AJAX

Date Posted: August 24, 2015, 3:33 am


I was loading the wp_editor thru AJAX, the editor shows up but the buttons for both Visual and Text Tab are missing. After some research I found an easy fix to this problem

The idea:

  1. Create a hidden div containing the wp_editor (place this code bellow the container where you are loading your ajax response)
  2. On AJAX success, get the contents of the hidden editor then append it to your AJAX response div container
  3. Reinitialize the editor: Remove the editor then add it back

Create a hidden div containing the wp_editor:

1
2
3
<div class="hidden-editor-container" style = "display: none;">
    <?php wp_editor('Default Content', 'tdmessagereply'); ?>
</div>

Server Side Structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static function cvf_td_veiw_frontend_message() {
   
    if(isset($_POST['cvf_action']) && $_POST['cvf_action'] == 'veiw_frontend_message' ) {
       
        $display .= '
        <article>
            <div class = "form-group">
                <label>'
. __('Reply', 'my-text-domain') . ':</label><br />
                <div class = "bg-primary hidden-reply-editor"></div>
            </div> 
            <input type = "submit" value = "'
. __('Send', 'my-text-domain') . '" class = "btn btn-primary reply_to_conversation" />
        </article>'
;
       
        echo $display;
    }
    exit();
}
add_action('wp_ajax_cvf_td_veiw_frontend_message', 'cvf_td_veiw_frontend_message') );
add_action('wp_ajax_nopriv_cvf_td_veiw_frontend_message', 'cvf_td_veiw_frontend_message') );

AJAX Request Structure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var data = {
    'action': 'cvf_td_veiw_frontend_message',
    'cvf_action': 'veiw_frontend_message'
};

$.post(global.ajax_url, data, function(response) {
   
    // After the response has been appended to the our front-end...
    if($(".cvf_td_conversation_messages").html(response)){
       
        // Get the contents of the hidden wp_editor
        reply_editor = $('.hidden-editor-container').contents();
       
        // Append the contents of the hidden wp_editor to div container
        $('.hidden-reply-editor').append( reply_editor );
       
        // Reinitialize the editor: Remove the editor then add it back
        tinymce.execCommand( 'mceRemoveEditor', false, 'tdmessagereply' );
        tinymce.execCommand( 'mceAddEditor', false, 'tdmessagereply' );
    }
});

Hope this tutorial makes a better day for someone 🙂

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me