How to call WP3.5 Media Library manager?

From the article How to use WordPress 3.5 Media Uploader in Theme Options (by codestag.com), as seen in Using the WordPress 3.5 Media Uploader within plugins (by mikejolley.com). Mike Jolley’s article has quite some nice tricks.

Important note: if the page where the uploader is going to be used doesn’t already have all media JS APIs, then wp_enqueue_media() has to be called.


So, supposing we have a button like this in a custom Meta Box:

<div class="uploader">
      <input type="text" name="settings[_wpse_82857]" id="_wpse_82857" />
      <input class="button" name="_wpse_82857_button" id="_wpse_82857_button" value="Upload" />
</div> 

The following script will call the new uploader and fill up the input text field #_wpse_82857 with the attachment path when Insert into post is clicked.

jQuery(document).ready(function($)
{
    var _custom_media = true,
        _orig_send_attachment = wp.media.editor.send.attachment;

    // ADJUST THIS to match the correct button
    $('.uploader .button').click(function(e) 
    {
        var send_attachment_bkp = wp.media.editor.send.attachment;
        var button = $(this);
        var id = button.attr('id').replace('_button', '');
        _custom_media = true;
        wp.media.editor.send.attachment = function(props, attachment)
        {
            if ( _custom_media ) 
            {
                $("#"+id).val(attachment.url);
            } else {
                return _orig_send_attachment.apply( this, [props, attachment] );
            };
        }

        wp.media.editor.open(button);
        return false;
    });

    $('.add_media').on('click', function()
    {
        _custom_media = false;
    });
});

Leave a Comment