How to upload files in wordpress – Source Code Version Only
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.




1 Comment
Perhaps better indentation would aid readability.