X

How To Upload User-Submitted Files to the Media Library

Snippets by IsItWP

Do you want to upload user-submitted files to the media library? This snippet will handle uploading files to your media library.

Instructions

  1. Add this code to your theme’s functions.php file or in a site-specific plugin.
  2. All uploaded files are stored in the $_FILES array, so you will need to loop through the $_FILES array and pass each file array to the upload_user_file() function. You can use this code in your form handler:

    if( ! empty( $_FILES ) ) {
      foreach( $_FILES as $file ) {
        if( is_array( $file ) ) {
          $attachment_id = upload_user_file( $file );
        }
      }
    }
    
  3. Remember that if you want your form to be able to handle file uploads, then you need to add the enctype="multipart/form-data" attribute to the <form> tag.
function upload_user_file( $file = array() ) {

      require_once( ABSPATH . 'wp-admin/includes/admin.php' );

      $file_return = wp_handle_upload( $file, array('test_form' => false ) );

      if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
          return false;
      } else {

          $filename = $file_return['file'];

          $attachment = array(
              'post_mime_type' => $file_return['type'],
              'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
              'post_content' => '',
              'post_status' => 'inherit',
              'guid' => $file_return['url']
          );

          $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );

          require_once(ABSPATH . 'wp-admin/includes/image.php');
          $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
          wp_update_attachment_metadata( $attachment_id, $attachment_data );

          if( 0 < intval( $attachment_id ) ) {
              return $attachment_id;
          }
      }

      return false;
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out How to Set Up Download Tracking in WordPress With Google Analytics

Comments   Leave a Reply

  1. Cool, is there a code that you can preview the file?

    1. I’m sure anything could be done, but it does not have a preview of the file.

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!