Upload file inside plugins options page

Wow… this one is not a simple one… it’s not a matter of calling the magic function uploadimages()… I wish it would 🙂

I’ve learned from a tutorial I cannot seem to find (but this one seems fair) and from analyzing other plugins.

The following is just a general orientation, sorry for not making a detailed manual. There may be flaws but hopefully you’ll manage to join the pieces and find the way to do your magic.

You’ll need to enqueue the following scripts and styles in your plugin’s page:

function my_admin_scripts() {
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
    wp_register_script('your-plugin-js', THIS_PLUG_DIR . 'js/uploader.js', array('jquery', 'media-upload', 'thickbox'));
    wp_enqueue_script('your-plugin-js');
}

function my_admin_styles() {
    wp_enqueue_style('thickbox');
}

The upload button and the image container.

<?php
$img = (isset($link->link_image) && '' !== $link->link_image) ? "https://wordpress.stackexchange.com/questions/53849/<img src="' . $link->link_image . '" >' : '';
$spanimg = sprintf('<div id="my-link-img">%s</div>', $img);
?>
<a id="upload_image_button" href="#"><?php _e('Set image', 'your-textdomain'); ?></a>
<?php echo $spanimg; ?>

And finally, the jQuery inside the file uploader.js where the trick happens:

jQuery(document).ready(function($) {    
    $('#upload_image_button').click(function() {
        formfield = $('#link_image').attr('name'); 
        tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
        return false;
    });

    window.send_to_editor = function(html) {
        imgurl = $('img',html).attr('src');
        imgsrc="https://wordpress.stackexchange.com/questions/53849/<img src=""+imgurl+'">';
        $('#link_image').val(imgurl); // this populates a text field with the image url
        $('#my-link-img').html(imgsrc); // this prints the image into a div
        tb_remove();
    }
});

These snippets were taken from a plugin of mine (which needs an update, as I learned quite a few things after releasing it).

Good luck!