I’m currently developing a new plugin and had the opportunity to play with the new Media Explorer in v3.5/3.6
The Random Chuck Norris Jokes Plugin
I found the documentation a bit lacking and so I’ve created a small plugin to demonstrate how you can easily create a new tab in the explorer window and then insert content back into the text editor.
Check out the plugin on GitHub
You don’t need much PHP code you need to get the plugin displaying content, there are 3 tasks we want to achieve.
1) Create the tab
add_filter('media_upload_tabs', 'chuck_add_media_tab');
function chuck_add_media_tab($tabs) {
$tabs['chuck_media'] = __('Insert Chuck Norris Joke', 'chuck_media');
return $tabs;
}
2) Attach JS and CSS files
add_action('media_upload_chuck_media', 'chuck_tab_iframe');
function chuck_tab_iframe() {
wp_register_style('chuck-media-css', plugins_url('css/media-tab.css', __FILE__));
wp_enqueue_style('chuck-media-css');
wp_enqueue_script('chuck-media-js', plugins_url('js/media-tab.js', __FILE__));
wp_iframe('chuck_tab_content');
}
3) Display code to the user in the tab
function chuck_tab_content() {
echo "<div class=\"chuck-norris-container\">"; // He can't really be contained.
echo " <p class=\"joke\"></p>";
echo " <a href=\"#\" class=\"refresh-joke\">refresh</a>";
echo " <a href=\"#\" class=\"insert-joke\">insert</a>";
echo "</div>";
}
Now you should see the tab working, the next step is to write a little bit of Javascript to add functionality to the tab. The code below is easy enough to understand, it gets jokes from http://api.icndb.com/jokes/random and outputs to the div containers we set up earlier.
The bit I struggled with for a while was the line
parent.wp.media.editor.insert(jokeToInsert);
The reason for this was that I needed parent. to access the wp functionality. This is because the tab is rendered in an iFrame and needs parent to traverse the DOM to the original document.
jQuery(document).ready(function($) {
function getNorrisJoke() {
jQuery.ajax({
url: "http://api.icndb.com/jokes/random/",
dataType: 'jsonp',
data: {cache: "true"},
success: function(data) {
jQuery('.chuck-norris-container p.joke').text(data.value.joke);
}
});
}
getNorrisJoke(); // Run the function on page load.
jQuery(document).on('click', 'a.refresh-joke', function() {
getNorrisJoke();
return false;
});
jQuery(document).on('click', 'a.insert-joke', function() {
var jokeToInsert = jQuery('.chuck-norris-container p.joke').text();
parent.wp.media.editor.insert(jokeToInsert); // This is the bit that killed me.
// Using parent.wp enables me to use the wordpress functionality here.
return false;
});
});
So view the example and start playing with the new feature!