我已经編寫了一个向媒體庫添加遠端託管映像的功能.是的。
但是,它不会在媒體庫中生成縮略圖-我相信標準做法也應该是構成一定範圍的圖像尺寸(?),但它不会。
$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
部分中正在發生(或未發生)
,我覺得它需要生成縮略圖。
註意,我没有將此圖像附加到帖子上。
最新回復
- 2020-5-191 #
相似問題
- wordpress:遷移後是否需要在媒體庫中重新註册所有映像?wordpressimageswordpressmedialibrarywordpressmigration2021-01-05 14:24
- wordpress:仅將媒體上傳到資料庫wordpressimageswordpressdatabasewordpressuploadswordpressmysqlwordpressmedia2021-01-02 06:25
- wordpress:在本地主機上上傳錯誤(至少,尚未線上測試)wordpressimageswordpressuploadswordpressadminwordpressmedia2020-11-19 20:53
- wordpress:內建的圖像延迟載入:是否為旧版瀏覽器提供了polyfill?wordpressimageswordpressjavascriptwordpressmedia2020-11-06 01:26
- wordpress:获取完整的圖像陣列wordpressimageswordpressadvancedcustomfieldswordpressmedialibrary2020-05-07 19:25
為了
wp_generate_attachment_metadata()
可以正常工作,因為它会建立縮略圖和其他中間/圖像尺寸,例如medium
和large
,圖片附件/發佈資料必须具有正確的MIME型別(post_mime_type
),尽管您確實在$attachment
中进行了設置 陣列(發佈資料),代碼中的這一部分有問题:其中
$filename
被定義為$filename = 'jana-eisenstein';
這是不帶擴充套件名的檔案(例如.png
),並且该變數的值在您的函式中保持不變,因此使用上面的代碼, 和ext
在維兹維兹 陣列是type
因此,
$wp_filetype
相当於false
,匯致圖片附件的MIME型別無效。要解決此問题,您可以將完整檔案路徑傳遞给
備用選項'post_mime_type' => $wp_filetype['type']
或使用'post_mime_type' => false
而不是wp_check_filetype()
:這基於使用
basename( $filename )
的示例 並自動呼叫$wp_filetype = wp_check_filetype( $uploadfile, null ); // pass full path $wp_filetype = wp_check_filetype( basename( $uploadfile ), null ); // OR this works, too
,因此您無需手動呼叫它. :)wp_update_attachment_metadata()