tienes que tener el post id, al que quieres añadirlo,
Subes la imagen en su ruta, y la linkas al post id , algo así :
Este es un código de ejemplo , adáptalo a lo que quieres hacer
$ponerimagen = "wp-content/uploads/imagen_" .$newpostid. ".jpg";
$filename = file_put_contents($ponerimagen, file_get_contents($url_imagen_principal));
// The ID of the post this attachment is for.
$parent_post_id = $newpostid;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $ponerimagen ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $ponerimagen ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $ponerimagen ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $ponerimagen, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $ponerimagen );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );