- Yes, pretty much.
- Yes.
When you upload an image to WordPress a few things happen. These might not be in the precise order, I’m going off memory, but it shouldn’t change much:
- It makes sure the image has a unique filename and puts it in the
wp-content/uploads
directory. - It creates an attachment post for the image.
- It saves the file path of the original image as post meta.
- It generates metadata for the image, including dimensions etc. and saves it as post meta.
- It uses registered WordPress image sizes to crate cropped and resized versions of the image which are saved in the uploads directory.
- It saves the file paths and dimensions of the resized versions of the image to post meta.
When an attachment is deleted from the media library, the original and resized versions of the image are deleted from the server.
What’s important to know in your situation is that when an image is deleted from the server, absolutely nothing happens in WordPress. The file will just be missing when WordPress attempts to find it.
WordPress also never scans the uploads directory and lists files in the media library. It’s not a file explorer, and only lists attachments from the database. It is build so all media management is done in WordPress. If you try to manage media directly on the server you will get unexpected results in the media library.
There’s a few functions you should be aware of for what you’re trying to do:
media_handle_upload()
– Saves a file submitted from a POST request and create an attachment post for it.media_handle_sideload()
– Similar tomedia_handle_upload()
, but you can use it for images that are already on the server somewhere.update_attached_file()
– If you have the path to a file, and want to update an existing attachment to use it, you can use this function.wp_generate_attachment_metadata()
– Saves all the meta data for the attachment, and generates the resized and cropped versions. You would want to run this after usingupdate_attached_file()
.
There’s more to it, but that’s an overview of what needs to happen for media in WordPress.