# Uploading a file within WordPress is actually pretty simple, you start by creating a form with the correct attribute to allow it to process files:
enctype="multipart/form-data" and an input of
When the form is posted an array
$_FILES is populated with all the file properties stored and access using the format
$_FILES['filename']['name'] - where 'filename' is the name of the file input in the form.
To actually perform the upload you use the built in function
wp_upload_bits() - here's my code:
$new_file = $_FILES['fileToUpload']; wp_upload_bits($new_file['name'], null, file_get_contents($new_file['tmp_name']));
PHP saves file uploads to a temporary location (hence
$new_file['tmp_name']) before moving them to their final location - in the case of WordPress that's the upload directory. The above code is all that's required to get the file in place but it will not show up in your media library because it is not referenced in the database. To fix that you use
wp_update_attachment_metadata( ) and pass it the required information.
I found a great post from Misha Rudrastyh that explained exactly how to do it. I omitted a few of the checks such as mime type and size, I also don't need to check if there is no file uploaded as I have the
required attribute on the file input within the form.
Misha's code performs a check to ensure the file has been properly moved from the temp location to the final location -
if( move_uploaded_file(...) ) - before creating an array and adding those details to the database using
Once all that is done I then display the full file path so that I can copy it into a post. The next thing I want to figure out is how to automatically place that path on the clipboard to automate things even further.