WordPress调整大小后删除原始图像?

5
在WordPress媒体库中,是否有一种方法可以在调整大小后删除原始图像?它似乎会保留原始图像,我认为这浪费了很多空间。

https://wordpress.org/plugins/image-sizes/ - Luca Angioloni
嗨@Jonny Jordan,我的回答有帮到你吗? - Raunak Gupta
3个回答

6

您需要使用wp_generate_attachment_metadata过滤器来操作上传的图片。

以下是代码:

add_filter('wp_generate_attachment_metadata', 'txt_domain_delete_fullsize_image');

function txt_domain_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;
}

代码应该放在你当前使用的子主题(或主题)的function.php文件中,也可以放在任何插件的php文件中。
代码已经经过测试并完全可用。
希望这有所帮助!

当您创建帖子时,特色图像中未显示图像。 - ztvmark
代码删除了-scaled.jpg,但没有删除最大的(原始)文件。 - Rafiozoo

2
我不知道这个问题的直接答案,保留原始图像以供内部 Wordpress 插件使用是一个好主意。
然而,您可以通过使用 AWS S3 插件来减少存储和成本: https://wordpress.org/plugins/amazon-s3-and-cloudfront/ 这将需要您先设置 AWS S3 存储桶。 如果这听起来不清楚,请随时提出与此相关的另一个问题。

0

适用于WordPress 5.6 这个可以显示特色图片

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');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接