問題描述

我使用了很多縮圖,但從來沒有使用原始檔案。為了節省空間,我想防止將原始檔案儲存在磁碟上,但只保留 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。