問題描述

由於我們的用户定期上傳〜 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。