問題描述
我使用了很多縮略圖,但從來沒有使用原始文件。為了節省空間,我想防止將原始文件保存在磁盤上,但只保留 100 像素的縮略圖。我該怎麼做?
謝謝丹尼斯
最佳解決方案
add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata )
{
$upload_dir = wp_upload_dir();
$full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
$deleted = unlink( $full_image_path );
return $metadata;
}
次佳解決方案
我在網絡上提供了另一種解決方案。它基於這裏接受的一個,但它更進一步。
在這裏接受的是刪除 main-image 並繼續。我發現的解決方案是通過為”large” 生成的圖像替換原始圖像。如果沒有定義 image-resolution,它將繼續進行。
這樣,確保每個腳本依靠原始圖像,仍然可以像以前一樣工作 – 例如連續重命名。
http://www.wprecipes.com/how-to-automatically-use-resized-image-instead-of-originals
編輯:
@dalbaeb 指出我在 blog-post 的評論中寫下了一個問題。我重寫了基於 API 的代碼,而不是在那裏提供的解決方案。這不是很大的區別,只是使用與 API 中相同的函數調用;)
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_filename = $image_data['sizes']['large']['file'];
// Do what wordpress does in image_downsize() ... just replace the filenames ;)
$image_basename = wp_basename($uploaded_image_location);
$large_image_location = str_replace($image_basename, $large_image_filename, $uploaded_image_location);
// 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']);
// Check if other size-configurations link to the large-file
foreach($image_data['sizes'] as $size => $sizeData) {
if ($sizeData['file'] === $large_image_filename)
unset($image_data['sizes'][$size]);
}
return $image_data;
}
add_filter('wp_generate_attachment_metadata', 'replace_uploaded_image');
EDIT2:
我在一個客户端上的代碼有一個問題,另一個 size-configuration 鏈接到 large-file 。我相應地更新了代碼。如果你有任何問題,請給我一個郵件。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。