this question 可能重复。为此,您需要使用各种内置的 WordPress 功能:
wp_insert_attachment()
set_post_thumbnail()
wp_generate_attachment_metadata()
wp_update_attachment_metadata()
wp_insert_attachment() 可能是您最重要的函数,因为它会返回您的附件(图像)ID。 set_post_thumbnail() 然后将这个附件 ID 和您的帖子 ID 设置为帖子中的特色图片。
当我过去这样做时,我还发现我必须使用上面的元数据函数来正确分配用于从导入中删除帖子的图像和它们的关联图像。
file_put_contents($oldfile, $image_data);
rename( $oldfile, $newfile );
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $newfile, $post_id );
if ( $set_thumb ) {
$res2= set_post_thumbnail( $post_id, $attach_id );
}
$attach_data = wp_generate_attachment_metadata( $attach_id, $newfile );
$update_attach_metadata = wp_update_attachment_metadata( $attach_id, $attach_data );