Adding Files to 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.


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.


Upload Files to the WordPress Media Library

5 سال پیش

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *

این سایت از اکیسمت برای کاهش هرزنامه استفاده می کند. بیاموزید که چگونه اطلاعات دیدگاه های شما پردازش می‌شوند.