Skip to content

Instantly share code, notes, and snippets.

@bcole808
Last active August 29, 2015 14:00
Show Gist options
  • Save bcole808/b31ed5101b1723e77dce to your computer and use it in GitHub Desktop.
Save bcole808/b31ed5101b1723e77dce to your computer and use it in GitHub Desktop.
How to implement the WordPress Media Uploader

WP Media Uploader implementation

Starting in WordPress version 3.5, a new multimedia uploader is available to developers! Wohooo! This allows users to pick or upload an image file and then have that object data returned to your javascript for use any way you like.

In your functions.php file

Make sure to call wp_enqueue_media() from within the admin_enqueue_scripts action hook. This magically adds all dependencies to the page. Includes sugar, spice, and everything nice.

add_action('admin_enqueue_scripts', my_enqueue_scripts);

function my_enqueue_scripts() {
  wp_enqueue_media();
}

In your HTML

You can bind the function to any action... but you probably want it to occur when the user clicks on a button:

<button class="custom_media_upload_button" />

If you want to use the returned value in a form, you may want some fields to store the data:

<input type="hidden" name="attachment_id" id="attachment_id" value="">
<input type="hidden" name="attachment_url" id="attachment_url" value="">
<img id="attachment_preview" src="" />

In your Javascript

Bind the following function to your media upload button.

$('.custom_media_upload_button').click(function(e) {

    e.preventDefault();

    var custom_uploader = wp.media({
        title: 'Custom Title',
        button: {
            text: 'Custom Button Text'
        },
        multiple: false  // Set this to true to allow multiple files to be selected
    })
    .on('select', function() {
        var attachment = custom_uploader.state().get('selection').first().toJSON();

        // Do some fun things with this data when it is available!
        console.log(attachment);

        // Example of the magical things we could do...
        $("#attachment_id").val(attachment.id);
        $("#attachment_url").val(attachment.url);
        $("#attachment_preview").attr('src', attachment.url);

    })
    .open();

});

Further reading:

http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/ http://codestag.com/how-to-use-wordpress-3-5-media-uploader-in-theme-options/ http://stackoverflow.com/questions/13847714/wordpress-3-5-custom-media-upload-for-your-theme-options#answer-16070511

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment