How do I programmatically add an image to a post?

I’m working on converting my old NucleusCMS blogs to WordPress. I have created a set of tables locally and began the conversion process. I’ve been fine right up to image “conversion”. I think I can pull the old image and add it to the library using this answer. After that, I’m sort of lost.

What I want to do is, having just programmatically added a media item (picture), then use that image by programmatically adding it to a specific post with the dimensions and alt text I just pulled (via regex) from the source I was working from.

Step 1. I need to get a pointer or id or something for the freshly added media.

I don’t 100% know what I am doing with WordPress itself so I do not know how to get a handle on the media I just added.

Step 2. I need to make that image be part of a post.

As for how I add it to the post (in the right size) in whatever format WordPress uses natively…

I need help with both steps.

2 Answers
2

Hey I used this code for something similar(I was also downloading remote image and uploading to WordPress site). Please have a look:

$image_url = $value;//This is the sanitized image url.
$image = pathinfo($image_url);//Extracting information into array.
$image_name = $image['basename'];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
$filename = basename($unique_file_name);
$postarr = array(
    'post_title' => $post_title,
    'post_content' => $post_content,
    'post_type' => 'post',//or whatever is your post type slug.
    'post_status' => 'publish',
    'meta_input' => array(
        //If you have any meta data, that will go here.
    ),
);
$insert_id = wp_insert_post($postarr, true);
if (!is_wp_error($insert_id)) {
    if ($image != '') {
        // Check folder permission and define file location
        if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'] . "https://wordpress.stackexchange.com/" . $filename;
        } else {
            $file = $upload_dir['basedir'] . "https://wordpress.stackexchange.com/" . $filename;
        }
        // Create the image  file on the server
        file_put_contents($file, $image_data);
        // Check image file type
        $wp_filetype = wp_check_filetype($filename, null);
        // Set attachment data
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => sanitize_file_name($filename),
            'post_content' => '',
            'post_status' => 'inherit',
        );
        // Create the attachment
        $attach_id = wp_insert_attachment($attachment, $file, $insert_id);
        // Include image.php
        require_once ABSPATH . 'wp-admin/includes/image.php';
        // Define attachment metadata
        $attach_data = wp_generate_attachment_metadata($attach_id, $file);
        // Assign metadata to attachment
        wp_update_attachment_metadata($attach_id, $attach_data);
        // And finally assign featured image to post
        $thumbnail = set_post_thumbnail($insert_id, $attach_id);
    }
}

Leave a Comment