I am making a small live preview area inside a meta box using jquery where i need to get content from tinymce editor. But it seem my script loads before tinymce, this returns null when i try to get content from editor field.
Enqueue:
add_action('admin_enqueue_scripts', 'wpk_popup_admin_script', 100);
function wpk_popup_admin_script($hook) {
global $post;
if( 'edit.php' != $hook && $post->post_type != 'wpk_popup' )
return;
if(is_admin()){
wp_enqueue_script( 'jquery' );
wp_register_script( 'wpk-popup-admin', plugins_url('/js/admin.js', __FILE__), array('jquery'), false, true);
wp_enqueue_script( 'wpk-popup-admin' );
}
}
Tried adding editor
on dependency but its no use. The script prints just before the tinymce configuration.
jQ Code for getting editor content:
html += jQuery('#content_ifr').contents().find('#tinymce').html();
Which returns NULL
.
Resolved:
Thanks to @birgire, I was able to solve the problem. Here is the final code.
add_action( 'after_wp_tiny_mce', 'custom_after_wp_tiny_mce' );
function custom_after_wp_tiny_mce() {
printf( '<script type="text/javascript" src="%s"></script>', plugins_url('/js/admin.js', __FILE__) );
}
For Getting or Inserting data I prefer to use tinymce api instead of jquery hack. So,
Getting Data
var content = tinyMCE.activeEditor.getContent();
Inserting Content
tinymce.activeEditor.execCommand('mceInsertContent', false, 'Text to insert goes here')
Adding scripts after TinyMCE:
You might check out the
before_wp_tiny_mce
andafter_wp_tiny_mce
hooks.If you take a look at the file
/wp-includes/class-wp-editor.php
you can see that theTinyMCE
settings scripts are not all loaded through the usualenqueue
methods, but some are displayed via:where the
editor_js
method contains this code:So if you want to add a custom script after all the
TinyMCE
scripts, you could emulate it’s own (non-elegant) way above through theafter_wp_tiny_mce
hook:This raises the question why not all the
TinyMCE
scripts are loaded via enqueue.The hook
admin_print_footer_scripts
is too late for adding new scripts via enqueue, so it could be that some of theseTinyMCE
scripts must be loaded very late on the page.Capturing the editor content with jQuery:
You could also try this snippet, enqueued the normal way:
to get the editor content.