I think @janw has got this one completely right, but I was unable to make one thing work. Jan inserts the media library button using:
do_action( 'media_buttons', 'default_featured_image' );
and then pre-empts the default action using:
jQuery('#default_featured_image_button').click(function () {...
The problem that I ran into is that inserting a media button in this fashion does not assign an id of "default_featured_image_button" to the link. In fact it does not add any id on the inserted link. So this is what I did to get it to work.
I added this line to my meta box callback function just after my input field:
<input id="upload_logo_button" type="button" value="Media Library Image" class="button-secondary" />
I then enqueued my custom jquery file and the thickbox css file, also in my functions.php file, using:
add_action('admin_enqueue_scripts', 'jhsir_load_image_set_js');
function jhsir_load_image_set_js() {
wp_enqueue_script( 'jhsir_image_set_script', get_stylesheet_directory_uri() . '/js/image-set.js', array('jquery','media-upload','thickbox') );
wp_enqueue_style( 'thickbox' );
}
Finally my image-set.js file included the following:
jQuery(document).ready(function($) {
var formfield = null;
$('#upload_logo_button, #upload_background_button').click(function() {
$('html').addClass('Image');
formfield = $(this).prev('input').attr('name');
formfield_id = $(this).prev('input').attr('id');
tb_show( '', 'media-upload.php?type=image&TB_iframe=true' );
return false;
});
// user inserts file into post.
// only run custom if user started process using the above process
// window.send_to_editor(html) is how wp normally handles the received data
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function( html ) {
var fileurl;
if(formfield != null) {
fileurl = $( 'img', html).attr('src');
$( "#" + formfield_id ).val(fileurl);
tb_remove();
$('html').removeClass('Image');
formfield = null;
} else {
window.original_send_to_editor(html);
}
};
});
You will note that I used variables to store the name and id of the input field that is just prior to the link that calls the jQuery. In that way this code can be used repeatedly on the same page. You would just need to assign a class to all buttons or use individual id's for the buttons in your jquery as I did. I hope this helps someone as Jan's answer did me.