David Ogilo

menu search

Inserting a media file into multiple TinyMCE editors in WordPress

Whilst adding custom meta boxes to a content type in wordpress, I noticed that when inserting a media file into a custom text editor it always gets added to the content text editor. The reason for this is because the active editor is hard coded in the source code, as shown below in wp-admin/js/media-upload.dev.js line 64:

if ( typeof tinyMCE != 'undefined' && tinyMCE.activeEditor )
	tinyMCE.activeEditor.windowManager.bookmark = tinyMCE.activeEditor.selection.getBookmark('simple');

I looked into fixing the issue, below is an explanation of how I did it. This fix can only be done via a plugin, so either create a new one or extend your existing plugin. Also, the custom text editor needs to be loaded in the meta box via the the_editor function

As stated above the active editor needs to be changed dynamically without amending the core wordpress source files. To do this, an onClick event needs to be added to the media buttons so that when clicked, the active editor is registered. Once the media modal dialog is loaded, again the active editor needs to be registered by checking the parent active editor that was initiated earlier. Below is the JavaScript source code:

var activeTinyEditor = '';
jQuery( document ).ready( function(){
	jQuery( '#media-buttons a' ).live( 'click', function(){
		var id = jQuery( this )
				.closest( '#editor-toolbar' )
				.siblings( '#editorcontainer')
				.children( 'textarea' )
				.attr( 'id' );
		activeTinyEditor = id;
	if ( parent != self )
		if ( typeof parent.tinyMCE != 'undefined' && parent.tinyMCE.activeEditor ) {
			parent.tinyMCE.get( parent.activeTinyEditor ).focus();
			parent.tinyMCE.activeEditor.windowManager.bookmark = parent.tinyMCE.activeEditor.selection.getBookmark('simple');

The JavaScript source above needs to be loaded when editing or adding a new post/custom post type. To do this we need to use the enqueueScript action hook as shown below:

add_action( 'admin_enqueue_scripts', 'myEnqueueScript' );
function myEnqueueScript()
	global $hook_suffix;
	switch ( $hook_suffix )
		case 'post.php':
		case 'post-new.php':
		case 'media-upload.php':
			wp_enqueue_script( 'post', plugins_url( 'my_plugin' ) . '/files/js/post.js', array( 'jquery' ), 1, true );
Tags: , , , , , ,

Old school browser detected!

Your browser is out of date, which means you can't use any of the site's required features. You can either upgrade your browser or switch to either Mozilla Firefox or Google Chrome