Hooking Wordpress media uploading in plugins

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">
//<![CDATA[
jQuery(document).ready(function($){

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

  send_to_editor = _ste;
  tb_remove();
};

$('a.thickbox').click(function(){
  if( typeof(send_to_editor) == 'function' ) {
    _ste = send_to_editor;
    send_to_editor = callback
  }
});

}); // document.ready
//]]>
</script>```

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.

Add an Image


And that’s all she wrote!

Featured