17

Does anyone know how o load wp_editor via AJAX in WordPress?

My markup and editor is getting loaded properly but editor controls are not getting loaded properly, it may be because Javascript is not running in AJAX call.

Any help would be appreciated.

  • It's a hell of a thing to get working. Check out some of the code from Carrington Build or Advanced Custom Fields (I think...). Just be prepared to be frustrated. – MikeNGarrett Jan 13 '14 at 2:09
7

The main problem are the missing scripts. The scripts enqueued in _WP_Editors::enqueue_scripts() are never printed. The same is true for _WP_Editors::editor_js().

So you have to do that in your AJAX callback handler. I have written a demo plugin and put it on GitHub: T5 AJAX Editor.

There is one class named Ajax_Editor. Its method render() prints the editor on AJAX requests.

public function render()
{
    if ( ! $this->validator->is_valid( TRUE ) )
        die( 'nope' );

    wp_editor( $this->data->get(), $this->editor_id, $this->settings );
    \_WP_Editors::enqueue_scripts();
    print_footer_scripts();
    \_WP_Editors::editor_js();

    die();
}

The exact order is important, an don’t forget the die() at the end. What doesn’t work yet is the media upload. I get a JavaScript error when I try to include that.

Note that calling print_footer_scripts(); will give you more than you expected: some plugins (Query Monitor for example) register their scripts even for AJAX requests, even if they don’t need them there.

  • Thanks so much! you saved me from 2 days trying to get work! the only thing with this, if you want to include it in a custom post type, it conflicts with other editor :( – numediaweb Oct 27 '14 at 16:45
  • for anyone looking, after WP 4.8 you can do this more easily (and cleanly) via the JS API wp.editor.initialize: wordpress.stackexchange.com/a/274608/76440 – majick Jun 18 at 7:11
0

After struggling with it, found the one line solution which works, in callback add:

tinymce.execCommand( 'mceAddEditor', true, element.id );

No idea why i couldnt find documentation inside tinymce.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.