WordPress media uploader fails after widget save

So basically, the moment I save the widget, it is no longer possible to open the media uploader. The error returned is

Uncaught TypeError: Cannot read property 'value' of null 

when an image was chosen (which leads to load-scripts.php), and no error (and still the media uploader does not show up) when no image was chosen after saving.

Read More

tl;dr callback stops responding after widget saving

The JS code I use is:

jQuery(document).ready(function($){
var custom_uploader;


$('.custom_media_upload').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.frames.file_frame = wp.media({
        title: 'Choose Image',
        button: {
            text: 'Choose Image'
        },
        multiple: false
    });

    //When a file is selected, grab the URL and set it as the text field's value
    custom_uploader.on('select', function() {
        attachment = custom_uploader.state().get('selection').first().toJSON();
        $('.custom_media_url').val(attachment.url);
    });

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

    return true;
});


});

The widget PHP code is

<img class="custom_media_image" src="<?php if ($instance['image'] != '') echo esc_attr( $image ); ?>" style="max-width:100px; float:left; margin: 0px     10px 0px 0px; display:inline-block;" />
<input class="custom_media_url" id="" type="text" name="<?php echo $this->get_field_name( 'image' ); ?>" value="<?php echo esc_attr( $image ); ?>" style="margin-bottom:10px; clear:right;">
<a href="#" class="button custom_media_upload">Upload</a>

What might be the problem?

EDIT: It looks like the callback gets cleared. When I attach the same callback through the console ite seems to work again.

Related posts

Leave a Reply

1 comment

  1. I still have no idea why jQuery’s hook gets cleared upon widget saving. I fixed the problem by adding a onclick tag to the anchor and changing the function’s signature.