問題描述
由於我們的使用者定期上傳〜 6MB 的影像以便在網站上使用 (並且不太熟悉如何首先調整大小),WordPress 將原稿儲存並將其大小調整為幾種不同的大小。
我想要一個使用上傳的影像的函式或外掛,將其調整到更易於管理的位置,然後替換原始影像。
我看到一些刪除原來的功能,但不能替換它,這意味著以後再重新生成縮圖是不可能的。我需要這個替換,所以使用者可以上傳大影像,並且如果需要,它將被自動調整大小並儲存以備日後調整大小。
最佳解決方案
將其新增到主題資料夾中的 functions.php 檔案。它用設定中設定的大影像代替原始影像。您可能需要設定新的影像格式,並將其用作新的原始大小。
function replace_uploaded_image($image_data) {
// if there is no large image : return
if (!isset($image_data['sizes']['large'])) return $image_data;
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
// $large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file']; // ** This only works for new image uploads - fixed for older images below.
$current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],"/"));
$large_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['large']['file'];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the large image
rename($large_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width'];
$image_data['height'] = $image_data['sizes']['large']['height'];
unset($image_data['sizes']['large']);
return $image_data;
}
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
次佳解決方案
上面的解決方案有一個討厭的 bug 。該解決方案可以作為新影像的魅力,但對於舊影像,您不應該與 $upload_dir['path']進行比較,因為這是當前上一個月的上傳資料夾。
替換以下內容:
//$large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file'];
$large_image_location = $upload_dir['basedir'] . '/'.$image_data['sizes']['large']['path'];
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。