Center for Strategic Communication

When creating a new WordPress plugin, I wanted to include the handy media uploader. Fortunately, Matt at Webmaster Source has a great tutorial on how to easily add this to your form.

However, when uploading the image it merely drops the URL to the new image into the field. Instead, I want the function to log the uploaded image ID and show a thumbnail.

First, you’ll need to add the following PHP to the form of your plugin:

//Action to get the image ID and echo a link to the image
add_action('wp_ajax_upload_image', 'upload_image');

function upload_image() {
    $image_id = $_POST['image_id'];
    $src = wp_get_attachment_image_src( $image_id, 'large' );
    echo '<a href="' . $src[0] . '" target="_blank">' . wp_get_attachment_image( $image_id, 'thumb' ) . '</a>';
    die();
}

Then, add the following Javascript code (special thanks to rofflox for the regex):

//Loads the image modal and sets the image ID in form
function get_image_modal() {

    //Set the button click
    jQuery('#upload_image_button').click(function() {

        //Shows the upload window
        tb_show( '', 'media-upload.php?type=image&TB_iframe=true' );

        return false;
    });

    //On clicking "Insert into post" button
    window.send_to_editor = function(html) {

        //Gets the classes of the image
        var classes = jQuery('img', html).attr('class');

        //Use regex to get the image ID
        var id = classes.replace(/(.*?)wp-image-/, '');

        //Loads the thumbnail
        get_image( id );

        //Adds the image ID to the hidden form field
        jQuery('#image').val(id);

        //Removes the upload window
        tb_remove();
    }
}

//Get the image thumbnail via AJAX
function get_image( id ) {

    //Sets the function name and image id for the AJAX call
    var data = {
        action: 'upload_image',
        image_id: id
    };

    //AJAX call to get the image thumbnail code ("ajaxurl" is pre-set by WordPress)
    jQuery.post(ajaxurl, data, function(response) {
        jQuery('.image_attach').find('.thumb_image').html(response);
    });
}

//Runs the get_image_modal function on document ready
jQuery(document).ready( function() {
    get_image_modal();
});
Note

WordPress just released a new media manager. While this should still work, it won’t load the new media manager. When I have a chance, I’ll update this to use the latest manager.