我编写了一个函数,将远程托管的图像添加到媒体库中。确实如此。
然而,它不会在媒体库中生成缩略图,我认为标准做法也应该是组成一系列图像尺寸(?),但事实并非如此。
$source_url = \'https://res.cloudinary.com/braincloud/image/fetch/c_thumb,g_face,w_275,h_275/https://contexthq.com/wp-content/uploads/promo329755877.png\'
$filename = \'jana-eisenstein\';
$img_title = \'Jana Eisenstein avatar\';
。 // cf. https://wordpress.stackexchange.com/a/50666/39300
function add_remote_image_to_library($source_url, $filename, $img_title) {
include_once( ABSPATH . \'wp-admin/includes/image.php\' );
// ****** 1. Set folder and filename ****** //
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir[\'path\'] . \'/avatars/\' . $filename.\'.\'.pathinfo($source_url)[\'extension\'];
// ****** 2. Get the image ****** //
$contents= file_get_contents($source_url);
// ****** 3. Upload the image ****** //
$savefile = fopen($uploadfile, \'w\');
fwrite($savefile, $contents);
fclose($savefile);
// ****** 4. Insert to Media Library ****** //
// Insert
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => $img_title,
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile);
// Meta data
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
文件将添加到正确的目录中。但是,在媒体库中,只有一个空白图像图标。。。该部分正在发生(或没有发生)某些事情// Meta data
, 我觉得它需要生成缩略图。请注意,我没有将此图像附加到帖子。