In a recent project, I’ve been working on a plugin in which the user needs to upload a file to a custom post type by using an input element (of type file
, obviously) rather than using the WordPress media uploader.
In addition to being able to upload the file, the user must also be able to view the file and remove the file (via Ajax) by an available anchor.
In order to do this, the plugin has to do the following:
- Upload the file to the `uploads` directory
- Save the file URL to the custom post type’s post meta data
- Save the file path to the custom post type’s post meta data
- Delete the file from the `uploads directory
- Clear the post meta data referencing the file
The primary reason that you have to store the file’s location on disk is because you can’t rely on PHP to delete a file via remote requests.
To that end, you need to be able to store not only where the file is on disk (for the sake of being able to delete), but also the URL of the file so that visitors or viewers can access the file via their browser.
Over the next two articles, I’ll share how to programmatically upload files in WordPress and save their associated meta data, and then I’ll share how to programmatically delete the files in WordPress as well as their associated meta data.
Continue reading