Creating custom metaboxes and the built in uploader

I’ve been browsing for a way to use my own up-loader in a custom metabox.

While the best way is to check out Matt’s post.

But the problem arose when I used the custom metabox and uploader on a post or page. It overwrote the insert to post feature, not allowing an image to be sent to the edit field.

If you follow Matt’s instructions you’ll have to modify two code snippets to make it work with posts and pages.

An example of a custom upload metabox field

An example of a custom upload metabox field

First, remove the if statements that will check if it’s a plugin or theme setting page. I’m sure there is a way to only apply this to post.php and page.php..

if (isset($_GET['page']) && $_GET['page'] == 'my_plugin_page') {
    add_action('admin_print_scripts', 'my_admin_scripts');
    add_action('admin_print_styles', 'my_admin_styles');
}

Second, change the javascript file to read:

jQuery(document).ready(function() {
	
	var formfield;
	
	jQuery('#Image_button').click(function() {
		jQuery('html').addClass('Image');
		formfield = jQuery('#Image').attr('name');
		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 would normally handle the received data

	window.original_send_to_editor = window.send_to_editor;
	window.send_to_editor = function(html){

		if (formfield) {
			fileurl = jQuery('img',html).attr('src');
			
			jQuery('#Image').val(fileurl);

			tb_remove();
			
			jQuery('html').removeClass('Image');
			
		} else {
			window.original_send_to_editor(html);
		}
	};

});

Of course, be sure to change the ID’s to read like your meta fields..

That’s it, now your media uploader with work with the editor and custom metabox.

Links