Unable to get Preview of Uploaded image within a Custom Meta box

I see your problem in the javascript. I’ve done something similar using the “on close” event of the wp.media object. You can use the “select event”, as you are actually doing, but I would use “on select” event mainly for events within the modal window (but it is just preference, you can use the “on select” if you want).

Here my suggested javascript code for you.

  jQuery(document).ready(function($){
      var custom_uploader;
      $('#insert-video-button').click(function(e) {
          e.preventDefault();
          //If the uploader object has already been created, reopen the dialog
          if (custom_uploader) {
              custom_uploader.open();
              return;
          }
          //Extend the wp.media object
          custom_uploader = wp.media({
              title: 'Choose Image',
              button: {
                  text: 'Choose Image',
              },
              multiple: false,
             // If you pretent a function only for images you can limit the media elements only to images
             library : { type : 'image'}
         });

         //When close, grab the url of the image where needed
        custom_uploader.on('close', function() {
            attachment = custom_uploader.state().get('selection').first().toJSON();
            $('#upload_image').val(attachment.url);
            $('.custom_preview_image').attr("src", attachment.url);
        });

       //Open the uploader dialog
       custom_uploader.open();
   });
});

This code should works with the HTML code you posted in the question. Note that actually it works only for ONE image, if you open the image selection window again and select a new image, the previous image will be replaced by the new selected image.

Leave a Comment