How to let a user select a media from the media library

Similar question can be found here and here. I use the following method, adapted from here:

When your theme/plugin initializes:

wp_enqueue_media();

Handle the media dialog in Javascript:

var wp_media_dialog_field;
function selectMedia() {
    var custom_uploader;
    if (custom_uploader) {
        custom_uploader.open();
        return;
    }
    custom_uploader = wp.media.frames.file_frame = wp.media({
        title: 'Choose Image',
        button: {
            text: 'Choose Image'
        },
        multiple: false
    });
    custom_uploader.on('select', function() {
        attachment = custom_uploader.state().get('selection').first().toJSON();
        wp_media_dialog_field.val(attachment.url);
    });
    custom_uploader.open();
}

Bind some buttons in Javascript to show the media dialog and store the field that will accept the return value:

jQuery('#my_button_1').click(function(e) {
    e.preventDefault();
    wp_media_dialog_field = jQuery('#my_field_1');
    selectMedia();
});

jQuery('#my_button_2').click(function(e) {
    e.preventDefault();
    wp_media_dialog_field = jQuery('#my_field_2');
    selectMedia();
});

Leave a Comment