Add WordPress Attachment Programmatically

WordPress offers a user-friendly interface for managing media. However, there are times when you might want to automate the process of adding captions to your images or other attachments.

Catatan Harian
Cissa Venatoria (1850-1883) print in high resolution by John Gould, Henry Constantine Richter and Charles Joseph Hullmandel. Original from The Minneapolis Institute of Art. Digitally enhanced by rawpixel.

WordPress offers a user-friendly interface for managing media, there are times when you might want to automate the process of adding captions to your images or other attachments.

Perhaps you’re importing a large number of images, and you want to provide consistent captions for each one. Or maybe you have a specific use case that requires programmatic captioning.

The Solution: A Custom Function

To achieve this, we’ll create a custom PHP function that allows you to set not only captions but also titles, alt text, and descriptions for your attachments.

public static function setAsPostAttachment($attachment_file, $post_id, $title = '', $alt = '', $description = '', $caption = '')
{
    if ($attachment_file === false) {
        return false;
    }

    // Check if the file exists
    if (file_exists($attachment_file)) {
        // Prepare the attachment data
        $attachment_data = array(
            'post_title'     => $title ? $title : sanitize_file_name(pathinfo($attachment_file, PATHINFO_FILENAME)),
            'post_content'   => $caption, // Set the caption as the post content
            'post_status'    => 'inherit',
            'post_mime_type' => mime_content_type($attachment_file),
        );

        // Insert the attachment
        $attachment_id = wp_insert_attachment($attachment_data, $attachment_file, $post_id);

        // Generate attachment metadata and update the post
        if (!is_wp_error($attachment_id)) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $attachment_file);
            wp_update_attachment_metadata($attachment_id, $attachment_data);

            // Set title, alt, and description for the attachment
            update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt);
            update_post_meta($attachment_id, '_wp_attachment_image_description', $description);

            // Set the featured image if you want to attach it as a featured image
            // set_post_thumbnail($post_id, $attachment_id);
        } else {
            // Handle errors if attachment insertion fails
            // echo 'Error attaching file to the post: ' . $attachment_id->get_error_message();
        }
    } else {
        // Handle the case where the attachment file doesn't exist
        // echo 'File does not exist: ' . $attachment_file;
    }
}

How to Use the Function

Using this function is simple. Just call it with the appropriate parameters when you want to attach an image or other media to a post.

setAsPostAttachment('path/to/your/image.jpg', $post_id, 'Custom Title', 'Custom Alt Text', 'Custom Description', 'Custom Caption');

Replace 'path/to/your/image.jpg' with the actual path to your media file, $post_id with the ID of the post to which you want to attach the media, and customize the title, alt text, description, and caption as needed.