Sorry for the low level of research but the media JS code was always a mystery to me, and googling doesn't show any current and reasonable answers.

The scenario is simple, I have a form in which I want to let the user either upload a new image or select one from the media library. Easiest way seems to be to open the add media modal and let it handle the actual upload if needed. so all I need is

  1. The easy part - open The media modal.
  2. The harder part - get the id and maybe the url of the selected media when it closes

Is it even possible without extending the modal in some way? I can probably live with the default text on the buttons, but it will be nice to change this as well.


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

When your theme/plugin initializes:


Handle the media dialog in Javascript:

var wp_media_dialog_field;
function selectMedia() {
    var custom_uploader;
    if (custom_uploader) {
    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();

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) {
    wp_media_dialog_field = jQuery('#my_field_1');

jQuery('#my_button_2').click(function(e) {
    wp_media_dialog_field = jQuery('#my_field_2');
| improve this answer | |
  • on custom_uploader.on('select', function () , use insert instead of select. – mghhgm Feb 15 '19 at 22:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.