在WordPress媒体库中,是否有一种方法可以在调整大小后删除原始图像?它似乎会保留原始图像,我认为这浪费了很多空间。
您需要使用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;
}
适用于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');