Once a page has loaded, how do I create a TinyMCE editor?
Putting a wp_editor
call in an AJAX request then displaying it gives this:
Visual and text tabs are nonfunctional, no toolbar, no active TinyMCE instance, just the html markup. I need to instantiate the JS component of TinyMCE, but how?
I’ve also tried making a call in my AJAX response PHP to _WP_Editors::editor_js();
, and I can see the response in the console using console.log and I see the JS script there, but it is not inserted into the DOM and it is never executed
Updated for TinyMCE 4
I’ve made some progress
Load a wp_editor in the initial page load in a hidden div, then do the AJAX call to grab the editor markup.
While in PHP, you will need to retrieve the IDs of the editors created via wp_editor calls. Unfortunately, the variables on the _WP_Editors class are private, but wecan get around this by using filters. To do this we start by calling the editor_js hook inside an output buffer. It will attempt to generate the needed settings and output the required JS, although this JS will not work when sent back via AJAX and inserted.
At the end of this call, the _WP_Editors class pases the mcesettings array through a filter, which we will use to make a copy that we can pull the editor IDs out of:
So after we’ve added this filter, we call out editor_js function:
We can now use our $mcesettings copy to fill in a list of IDs:
The ids array can now be sent back in the AJAX response along with the html.
Once in the browser, we can insert the html into the page, and then using our editor_ids, we can instantiate the TinyMCE instances like this:
Because we don’t have the ability to generate the necessary TinyMCE settings ourselves to match the WordPress style, we instead steal them from the instance we created in the initial page load, and make copies. We then modify the copies to use the correct element IDs and proceed as usual, checking that the elements dont already have an instance.
Issues