Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to upload images in my custom plugin options page.

<form action="?page=slideshow_options" method="post">
    <input type="file" name="async-upload" id="async-upload">
    <input type="submit" name="html-upload" id="html-upload" class="button" value="Upload">
</form>

If I try to check wether submit button was clicked with isset I get some weird errors. How can I get it to call a function uploadimages() for example?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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) ? '<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 = '<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!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.