Using WordPress Media Uploader (wp.media)

I am writing this post as of WordPress 4.0, so this has nothing to with the ‘thickbox’ implementation in older versions of WordPress. It has been a long while since the new media library was implementated, but it has not been widely documented.

Tom McFarlin has written quite a comprehensive series titled Getting Started with the WordPress Media Uploader. However, his code had only covered usage of it in a edit/add post setting.

When using wp.media, there are a few things that we are interested. The first one is how to define the media frame. Tom has defined it this way:

file_frame = wp.media.frames.file_frame = wp.media({
    frame: 'post',
    state: 'insert',
    multiple: false
 });

Note that frame: 'post' defines that our frame will be similar to the one we see when we add media in the tinymce editor. There are cases when we are using the media frame apart from the Post setting (e.g. in theme options or a plugin settings page), we need to define it as frame: select' , and state: 'insert' has to be removed.

Also, there are more arguments that the wp.media object can take. Doing a console.log on file_frame after defining it might be useful if you want to dig deeper. But the below is what I’ve used in most cases:

file_frame = wp.media.frames.file_frame = wp.media({
   className: 'media-frame foundation-image-frame',
   frame: 'select'
   multiple: false,
   title: 'Select Media',
   library: { 
      type: 'image' // limits the frame to show only images
   },
   button: { 
      text : 'Select'
   }
});

The second thing that we are interested in is how to capture the event when we have selected the image(s) and clicked on the Select button.

Tom has defined it for a Post Setting this way:

file_frame.on( 'insert', function() {
   // Do things on insert event
});

As expected, this will only work for frame: 'post' . For frame: 'select', we will have to do this:

file_frame.on( 'select', function() {
   // Do things on select event
});

Alright, hope this is useful!

Leave a Comment