0

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.

1 Answer 1

1

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();
});
1
  • on custom_uploader.on('select', function () , use insert instead of select.
    – mghhgm
    Commented Feb 15, 2019 at 22:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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