使用时wp_handle_sideload
正如@xvilo在评论中指出的那样,它并没有创建wordpress在媒体库中显示图像所需的元数据。因为我看不到wp_handle_sideload
函数正在将数据写入数据库,我不明白为什么文件会显示在媒体库中。因此,在你的方法中,你错过了wp_insert_attachment
(正如你自己所说)和wp_generate_attachment_metadata
.
$temp_file = download_url( $url, 5 );
$file = array(
\'name\' => basename($url),
\'type\' => \'image/jpg\',
\'tmp_name\' => $temp_file,
\'error\' => 0,
\'size\' => filesize($temp_file),
);
$overrides = array(
\'test_form\' => false,
\'test_size\' => true,
);
// Move the temporary file into the uploads directory
$results = wp_handle_sideload( $file, $overrides );
// Write attachment to db
$attachment = [
\'post_title\' => basename($results[\'file\']),
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
\'post_mime_type\' => $results[\'type\'],
];
$attachment_id = wp_insert_attachment( $attachment, $results[\'file\'] )
// Generate the attachment\'s meta data
wp_generate_attachment_metadata( $attachment_id, $results[\'file\'] );
或者您可以使用
media_handle_sideload 函数,因为这个函数已经为您完成了。
$attachment_id = media_handle_sideload( $file_array, 0 );
之后,您可以使用
set_post_thumbnail( $post, $attachment_id );