诀窍在于media_sideload_image()
和set_post_thumbnail()
. media_sideload_image()
假设您可以获取图像的URL,无论它是否存在于/wp-content/
或者其他地方(甚至其他网站)。只要您可以通过编程方式引用图像的URL,类似这样的操作就可以了。
$image = \'image.jpg\';
$media = media_sideload_image($image, $post->ID);
if(!empty($media) && !is_wp_error($media)){
$args = array(
\'post_type\' => \'attachment\',
\'posts_per_page\' => 1,
\'post_status\' => \'any\',
\'post_parent\' => $post->ID
);
// reference new image to set as featured
$attachments = get_posts($args);
if($attachments){
foreach($attachments as $attachment){
set_post_thumbnail($post->ID, $attachment->ID);
// only want one image
break;
}
}
}