I'm not too familiar with Imagick, but if you can get a URL for the image you've created with it, then the rest is fairly straightforward using WordPress's media_sideload_image()
function. Here's a basic example that would work from wp-admin area(like settings page). Note that it looks like you'd use your $id
variable in place of my $post_id
:
// load image from URL into media library, set a post as its parent, and return new attachment's id
$attachment_id = media_sideload_image( $image_url, $post_id, $img_title, 'id');
if( !is_wp_error( $attachment_id ) ) { // if no error returned...
// ...Set above loaded image as the featured image of the current post
set_post_thumbnail($post_id, $attachment_id);
}
Note that Codex says third param of media_sideload_image sets description of the image, but it sets image title. Also, they just added the fourth parameter for returning the attachment id in 4.8, so hopefully you're up to date.
More Info:
Also note that if you're implementing this in the front end you'll need to include the following three files in your script so that media_sideload_image can handle the uploading, etc it does for us:
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');