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.

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>

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