WordPress: Media Uploader for Meta Boxes
so i’ve been running into a nagging issue with wordpress’ new instance of its media uploader (released in v3.5)
if i had a meta box with an image uploader, it would conflict with the standard “Add Media” button for the editor
previous code
uploader.js
jQuery(document).ready(function() { var form_field; jQuery('.button-upload').click(function() { form_field = '#' + jQuery(this).next('input').attr('id'); tb_show('', 'media-upload.php?type=image&TB_iframe=true'); return false; }); window.send_to_editor = function(html) { imgurl = jQuery('img',html).attr('src'); if(!imgurl){ imgurl = jQuery(html).attr('src'); } if (jQuery(form_field).length > 0) { jQuery(form_field).val(imgurl); } tb_remove(); } });
updated code
uploader.js
jQuery(document).ready(function($){ var _custom_media = true, _orig_send_attachment = wp.media.editor.send.attachment; $('#DIV_ID_GOES_HERE .button').click(function(e) { var send_attachment_bkp = wp.media.editor.send.attachment; var button = $(this); var id = button.attr('id').replace('_button', ''); _custom_media = true; wp.media.editor.send.attachment = function(props, attachment){ if ( _custom_media ) { $("#"+id).val(attachment.url); } else { return _orig_send_attachment.apply( this, [props, attachment] ); }; } wp.media.editor.open(button); return false; }); $('.add_media').on('click', function(){ _custom_media = false; }); });
make sure to add this to your functions.php
function example_post_class_meta_box( $object, $box ) { wp_register_script('my-uploader', get_bloginfo('template_directory') . '/js/uploader.js', array('jquery','media-upload','thickbox')); wp_enqueue_script('my-uploader'); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); wp_enqueue_style('thickbox'); ... blah blah blah ... <p> <input name="extra_featured_image_button" id="extra_featured_image_button" value="Choose Extra Featured Image" /> <input type="text" size="75" id="extra_featured_image" name="extra_featured_image" value="<?php echo get_post_meta($object->ID, '_extra_featured_image', true); ?>" /> </p>
in my research, i also found this, but i haven’t tried it out