WordPress Media Library: Programmatic Upload and Management

How to programmatically upload images and manage media in WordPress using code, including sideloading, attachment creation, and media handling.

Programmatic media management lets you upload images, create attachments, and manage the media library from your plugin code. This is essential for plugins that need to download and store images from external sources, generate images dynamically, or import media from other systems.

Uploading Files

Use wp_upload_bits() to upload a file from a binary string or stream. This function stores the file in the uploads directory and returns the file path and URL. For files already on the server, use wp_upload_dir() to get the upload directory path and copy the file there manually.

Sideloading External Files

Use media_sideload_image() to download and import images from external URLs. This function downloads the remote image, saves it to the uploads directory, creates an attachment post, and generates thumbnails. Use it for importing featured images, user avatars, or any external media.

Creating Attachments

Use wp_insert_attachment() to create an attachment post for an uploaded file. Set the post_mime_type based on the file type, guid to the file URL, and post_parent if attaching to a specific post. Run wp_generate_attachment_metadata() and wp_update_attachment_metadata() to generate thumbnails and store metadata.

Getting Attachment Data

Retrieve attachment data with wp_get_attachment_image() for HTML image output, wp_get_attachment_url() for the file URL, wp_get_attachment_metadata() for the metadata array including sizes, and wp_get_attachment_image_src() for a specific image size URL.

Deleting Media

Use wp_delete_attachment() to remove media from the library. This function deletes the attachment post, the main file, and all generated thumbnail sizes. Set the second parameter to true to force deletion without sending to trash. Use wp_delete_file() to delete a specific file from the filesystem.

The Bottom Line

Programmatic media management is essential for plugins that handle external images or bulk media operations. Use media_sideload_image() for downloading remote files, wp_insert_attachment() for creating attachments, and wp_delete_attachment() for cleanup. The WordPress media API handles file storage, thumbnail generation, and metadata automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *