Programmatically uploading files to WordPress is really just the same as uploading files from any source location to a destination.

That is to say, there are a number of PHP functions all of which make it pretty easy to deal with file-level operations, grabbing files from one location, and moving them to the next.

And yes, there are some nuances that can come with PHP’s configuration such that you may not be able to write to certain directories, perform certain options via HTTP, and so on. All of these can be managed by either changing up the configuration or by changing the way in which files are handled by the code.

The WordPress Media Library

One thing that WordPress offers that manual uploads don’t manage is adding files – specifically media types – to the Media Library after uploading a file. This is relatively easy to do given media_sideload_image.

But let’s say the situation is a little more complex.

Adding Files to the WordPress Media Library

Say that the setup is something like this:

  • You have files located on the root of the server
  • You need to move the files to the `uploads` directory
  • You need to add the files to the Media Library

There are a number of reasons that files may exist on the server. Perhaps you don’t want to grant the user access to the CMS, or perhaps it’s just easier for the person to drop the files into a directory via FTP and have a cron job pick it up and handle the rest.

Whatever the case, here’s a function that will locate the files in a subdirectory called my-files in the root of a WordPress installation, upload the file, and then write to the error log if the upload fails.

Note that in the code above we’re working both with the upload directory (using the path index of the $uploads array) and with the upload URL (using the url index of the $uploads array). This is because, in most cases, copy requires that the operation be done using the file system rather than remote calls using HTTP.

Furthermore, not much is happening after the image has been uploaded. That is, the code really only writes to a file if there’s a problem; otherwise, it’s assumed to have worked.

This is usually better handled by giving some type of feedback. Since implementations vary, that’s one of those things that’s easier to implement on a one-on-one basis rather than trying to give some type of prescriptive advice in a single blog post.

Regardless, this will make it possible to upload files to the WordPress Media Library when the files already exist on the server.

Share:

Leave a Reply