Upload to the Media Library From Your Plugin

There are a variety of reasons you may want or need to include an upload form inside your theme or plugin. One thing that bugs me, though, is when the image (or whatever) that I’ve uploaded isn’t available in the Media Library. I don’t want to have to reupload an image just so I can reuse it in a blog post.

The solution is pretty easy – let WordPress do the dirty work for you.

<?php
if ( isset( $_FILES[ 'some-file' ][ 'name' ] ) && !empty( $_FILES[ 'some-file' ][ 'name' ] ) ) {
    $upl_id = media_handle_upload( 'some-file', 0 );
    if (is_wp_error( $upl_id )) {
        echo '<div class="error"><p>'. $upl_id->errors['upload_error']['0'] .'</p></div>';
    }
    else {
        echo '<div class="updated"><p>"'. get_the_title( $upl_id ) .'" was uploaded!';
        echo wp_attachment_is_image( $upl_id ) ? '<br />' . wp_get_attachment_image( $upl_id ) : '';
        echo '</p></div>';
    }
}
?>
<form action="" method="post" enctype="multipart/form-data">
<p><input type="file" class="button" name="some-file" id="some-file" />
<input type="submit" class="button-primary" value="Upload"/>
<input type="hidden" name="submitted-some-file" /></p>
</form>

This is a very simple example, of course. Go play with it

One thought on “Upload to the Media Library From Your Plugin”

  1. d3xt3r_86

    hey…this is cool.
    do you happen to know hot to give a special id for the files uploaded with this form and how to get it on the front? šŸ™‚

    thanks

Leave a Reply

Your email address will not be published. Required fields are marked *