How to upload files in wordpress – Source Code Version Only

Advertisement:

If you ever need to build a custom plugin that creates a page with a form and that form has file inputs, you will have to upload those files properly. Here’s how you do it:

Wordpress has a function for this and it’s called wp_upload_bits (for more info about the function click here).

Here is a example on how to use it:

if($_FILES["inputFileName"]["name"]!=”") {
$file = file_get_contents($_FILES["inputFileName"]["tmp_name"]);
$xupload = wp_upload_bits($_FILES["inputFileName"]["name"], null, $file);
}

if($_FILES["inputFileName"]["name"]!=”") {
$file = file_get_contents($_FILES["inputFileName"]["tmp_name"]);
$xupload = wp_upload_bits($_FILES["inputFileName"]["name"], null, $file);//array with path, url and error
}

The if statement checks if a file has been selected for upload.. if none is selected in that field name, wp_upload_bits will not run. If a file is ready for upload, wp_upload_bits will upload the file in your uploads dir under wp-content and it will return a array that will be passed in this case to the $xupload variable. The array contains details about the uploaded file(path and url). Array also has a error parameter in case something goes wrong.

Click a icon to share:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Wikio
  • Yahoo! Buzz
  • LinkedIn
  • Live
  • RSS
  • StumbleUpon

Tags:

1 Comment

  1. scribu says:

    Perhaps better indentation would aid readability.