There are many use cases for allowing users to upload files from the frontend, but the trick is making sure the file is uploaded and saved in the WordPress media library correctly. You can easily use standard PHP functions to handle the upload and then store the file wherever you like, but then you won’t be able to take advantage of the media attachment system that WordPress uses. An image that is uploaded correctly, for example, will have all the various sizes available as well as the meta data, such as title, description and caption. You will also be able to edit all of this from the media library in your WordPress dashboard.
This snippet will handle the upload for you and save the file in your media library correctly. All you need to do is pass the uploaded file array to the function – all uploaded files are stored in the
$_FILES array so you just need to loop through that and upload each file from there. The function will return the ID of the attachment so you can handle any further processing from there. I’ve also included a basic usage example below.
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