Hooking Wordpress media uploading in plugins

  • 2/14/2011

WordPress features a user-friendly media management system that takes all the mystery of FTP out of uploading, editing, and presenting multimedia to blog audiences. It’s a great tool for authors and editors, but it can also save plugin authors the trouble of writing their own upload scripts. Here’s how to take advantage in three easy steps:

First, make sure that a few required scripts and styles are included in an action hook:

add_action( 'admin_init', 'init_styles_n_scripts' );

function init_styles_n_scripts() {

  wp_enqueue_script( 'thickbox' );
  wp_enqueue_script( 'media-upload' );

  wp_enqueue_style( 'thickbox' );

Next, add the following javascript into the page where you’ll be accessing the editor from. The general idea is to temporarily replace wordpress’s send_to_editor callback with one of our own prior to showing the media upload thickbox. As soon as the thickbox is closed, the callback will be called and the send_to_editor function reset to the wordpress default.

<script type="text/javascript">

var _ste;
var callback = function( image_url ){
  // do something with image_url...

  send_to_editor = _ste;

  if( typeof(send_to_editor) == 'function' ) {
    _ste = send_to_editor;
    send_to_editor = callback

}); // document.ready

Finally, add a media upload link to the HTML of the page. You might consider using a custom class (and editing the jQuery selector in the script above) to keep your custom links straight from any generated by WordPress or the TinyMCE editor.

<a href="media-upload.php?type=image&TB_iframe=1&tab=library" 
class="thickbox my-thickbox" title="Add an Image">Add an Image</a>

And that’s all she wrote!

Hey, it's RJ—thanks for reading! If you enjoyed this post, would you be willing to share it on Twitter, Facebook, or LinkedIn?