Simple upload field for WordPress plugins/themes

With this you can upload images through your plugin/theme. They are saved as attachments. Please add nonce fields for security reasons.

Raw
<?php
/**
 * Form builder helper
 *
 * @param string $label Field label
 * @return none
 */
function fileupload( $label ) { ?>
  <tr>
    <td class="left_label"> <?php
      echo $label; ?>
    </td>
    <td>
      <form name="uploadfile" id="uploadfile_form" method="POST" enctype="multipart/form-data" action="<?php echo $this->filepath.'#uploadfile'; ?>" accept-charset="utf-8" >
        <input type="file" name="uploadfiles[]" id="uploadfiles" size="35" class="uploadfiles" />
        <input class="button-primary" type="submit" name="uploadfile" id="uploadfile_btn" value="Upload"  />
      </form>
    </td>
  </tr>  <?php
}

/**
 * Handle file uploads
 *
 * @todo check nonces
 * @todo check file size
 *
 * @return none
 */
function fileupload_process() { 
  $uploadfiles = $_FILES['uploadfiles'];

  if (is_array($uploadfiles)) {

    foreach ($uploadfiles['name'] as $key => $value) {

      // look only for uploded files
      if ($uploadfiles['error'][$key] == 0) {

        $filetmp = $uploadfiles['tmp_name'][$key];

        //clean filename and extract extension
        $filename = $uploadfiles['name'][$key];

        // get file info
        // @fixme: wp checks the file extension....
        $filetype = wp_check_filetype( basename( $filename ), null );
        $filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
        $filename = $filetitle . '.' . $filetype['ext'];
        $upload_dir = wp_upload_dir();

        /**
         * Check if the filename already exist in the directory and rename the
         * file if necessary
         */
        $i = 0;
        while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
          $filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
          $i++;
        }
        $filedest = $upload_dir['path'] . '/' . $filename;

        /**
         * Check write permissions
         */
        if ( !is_writeable( $upload_dir['path'] ) ) {
          $this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
          return;
        }

        /**
         * Save temporary file to uploads dir
         */
        if ( !@move_uploaded_file($filetmp, $filedest) ){
          $this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
          continue;
        }

        $attachment = array(
          'post_mime_type' => $filetype['type'],
          'post_title' => $filetitle,
          'post_content' => '',
          'post_status' => 'inherit'
        );

        $attach_id = wp_insert_attachment( $attachment, $filedest );
        require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
        wp_update_attachment_metadata( $attach_id,  $attach_data );
      }
    }
  }
}
?>

13 comments

  1. avatar
    wrote this comment on

    hello, nice code, but i need to include it into a plugin option page.

    What i need to do is upload a custom logo from pc and append preview into same page.

    i use your code, but in my plugin doesn't work; no error message, simply do not upload file.

    How i can solve this big trouble? thanks

  2. avatar
    wrote this comment on

    Hi Pigi, if you have problems with your code you should debug it, using some debugger or adding logging output. If you're having problems with a specific line of my code I can probably help you.

  3. avatar
    wrote this comment on

    hello,
    i am also using this code. in my form when i upload pictures it works, but the metadata that is generated is much different from what is generated when i upload the same picture from the media panel in the admin page.

    just to give an example, no thumbnail is created. do you know how to make it work?
    thanks!

  4. avatar
    wrote this comment on

    I think you have to use wp_generate_attachment_metadata() to do that, but I haven't tested this.

  5. avatar
    wrote this comment on

    Nice but Iam a newbie, can you explain how to step by step use this plugin? I have installed on my wordpress

  6. avatar
    wrote this comment on

    I written the detail and simple code to upload file through add_meta_box function. check the following article.
    http://wordpressapi.com/2010/11/22/file-upload-with-add_meta_box-or-custom_post_type-in-wordpress/

  7. avatar
    wrote this comment on

    Nice, thanks for sharing!

  8. avatar
    wrote this comment on

    Check sony's link below :-)

  9. avatar
    wrote this comment on

    Oh, there was an error in the wp_insert_attachment() call, you're supposed to pass the absolute path to the file. It's fixed in the paste now.

  10. avatar
    wrote this comment on
    what shoud I do if I want change the directory upload to a different directory than wordpress upload directory
  11. avatar
    wrote this comment on
    Hrm, no idea tbh. It's been a while I've used this.
  12. avatar
    wrote this comment on
    your url doesn't open.it seems to be error
  13. avatar
    wrote this comment on
    Generally speaking, it's a good idea to avoid domains with "wordpress" in them, it's a registered trademark..

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo