Using the media uploader in a custom plugin

The output code of widget’s form method is added to page once for every instance of the widget (included the “dummy” instance contained in the “Available widgets” panel), so in your case the javascript code that defines the window.send_to_editor function may appear more than once, and the last instance overwrites the previous ones.
There are at least two reasons for not output javascript code by the form method:

  1. When you create a new instance of a widget (with drag & drop), the html code of the “dummy” (marked with __i__ index) is copied to the newly created widget and the index is replaced with a number, but the event handlers are not copied, so the new widget may not behave as expected.
  2. When you save a widget, the data is sent via ajax to the server and the output of the form method is sent back to the page and then added to the DOM dynamically. According to jQuery documentation, “any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string”, and this may lead to odd behaviors (moreover not all browsers behave the same way about this).

I recommend you to put your javascript code in a separate js file, and include in the page head by using wp_enqueue_script and use the jQuery live method to add event handlers. You may use a generic event handler for all instances and then look for the proper DOM elements to apply the relevant actions. Example:

jQuery('input[id^=uploadi]').live('click', function() {
     formfield = jQuery('input[id^=qrimage]', jQuery(this).closest('.widget')).attr('name');
     tb_show('', 'media-upload.php?type=image&TB_iframe=1');
     return false;
});

Note: change qrimage selector in the above code (not tested) to whatewer your field prefix is.

P.s. I also noticed a typo in the url media-upload.php?type=image&amp&TB_iframe=1

Leave a Comment