Adding the WordPress Uploader to Your Theme or Plugin

There are some tutorials out there similar to this, but WordPress has since updated their media uploader, making those tutorials obselete. This code is essentially a combination of the best ones I’ve found

Javascript

first, you’ll want to save this code into a .js file, say “uploader.js

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

    $('.media-button').click(function(e) {
        e.preventDefault();
        formfieldID=jQuery(this).next().attr("id");
        formfield = jQuery("#"+formfieldID).attr('name');
        //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();
            jQuery("#"+formfieldID).val(attachment.url);
        });
 
        //Open the uploader dialog
        custom_uploader.open();
    });
});

So when something that’s classed as “button” (preferably a button input), it’ll fire this script, opening the new media uploader. Once you find your image, click “Choose Image” and the image’s file path will be added to the next field, which should be an input text field.

PHP

Great! Now if you want to add the media uploader to a meta box, do the following…

(For brevity, I’m not going to explain how to create meta boxes)

queue up the uploader.js script within your meta_box function

function blah_blah_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');

...

To call it, add an input of type button and give it the “button” class.

    <p>
      Image<br />
      <input type="button" class="media-button button" name="custom_image_btn" value="Choose Image" />
      <input type="text" size="75" id="custom_image" name="custom_image" value="<?php echo get_post_meta($object-/>ID, '_custom_image', true); ?>" class="large-text" />
    </p>

That’s it — the best part is that you can have MULTIPLE uploaders on the page. A lot of the help out there only allowed for one per page, which doesn’t work for every situation.

Test it out and let me know if there are any issues.

Leave a Reply