Answers:
将其添加到主题文件夹中的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');
我可以建议对上述答案的代码进行更新吗?不幸的是,在较新版本的Wordpress中,不再为文件大小提供键“路径”。因此,要使其适用于较早的帖子上传,我们应该首先从原始图像中获取当前子目录,然后使用该子目录来创建大型图像的位置路径。
因此,替换此行:
$large_image_location = $upload_dir['basedir'] . '/'.$image_data['sizes']['large']['path'];
通过这两行:
$current_subdir = substr($image_data['file'],0,strrpos($image_data['file'],"/"));
$large_image_location = $upload_dir['basedir'] . '/'.$current_subdir.'/'.$image_data['sizes']['large']['file'];
我在这里发布了另一个非常类似的问题,但认为值得重新发布。
我上面的代码有问题,实际上对我有用的是更改这些行:
unlink($uploaded_image_location);
rename($large_image_location, $uploaded_image_location);
与:
$file_to_be_copied = $large_image_location;
$copied_file_name = $uploaded_image_location;
//make a copy of the large image and name that the title of the original image
if (!copy($file_to_be_copied, $copied_file_name)) {
echo "failed to copy $file...\n";
}
我在此处发布了完整的代码和更多说明: 删除原始图像-保留缩略图吗?