Insert Featured image from Feed

You will need to get the images onto your server and into the library. From that point you will be able to attach them to the post. You can only have 1 featured image so this needs to be adjusted to set the featured once but still download all the images and attach them to the post.

I’m using media_sideload_image in this example but you could use wp_insert_attachment (there is another example on that page).

// the new post has been created
$post_id = wp_insert_post($post_data, $wp_error);

// now we'll deal with the images

$image_ids = array();

foreach($data[ 'images' ] as $inx => $url) {

    // add external image to our library
    $src = media_sideload_image(rawurldecode($url), $post_id, NULL, 'src');

    // convert to attachment src -> ID -> post
    $attach_id = attachment_url_to_postid($src);

    // grab the id so we can add to the post when we're done
    $image_ids[] = $attach_id;

    // access to attachment post
    // $attach_post = get_post($attach_id);

    // set the image's parent id to the post
    wp_update_post(array('ID' => $attach_id, 'post_parent' => $post_id));

    if($inx === 0) {
        // add the first image as the post's featured image
        add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
    }
}

// add the ids onto the post's meta to use later -- store as simple string
add_post_meta($post_id, '_images', implode(',', $image_ids), true);

This code has not been tested


post_images is not a property of WP_Post so they need to be associated another way. Also many of those other properties should be added using add_post_meta instead of trying to add on the post itself – take a look at custom fields.

Leave a Comment