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


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

    var custom_uploader;

    $('.media-button').click(function(e) {
        formfield = jQuery("#"+formfieldID).attr('name');
        //If the uploader object has already been created, reopen the dialog
        if (custom_uploader) {
        //Extend the object
        custom_uploader = ={
            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();
        //Open the uploader dialog;

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.


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


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

      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" />

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.

Related Posts