Php 上传时自动调整Wordpress图像的最大宽度和高度?

Php 上传时自动调整Wordpress图像的最大宽度和高度?,php,image,wordpress,Php,Image,Wordpress,我创建了一个博客,一些用户可以通过Wordpress仪表板上传图片。由于原始图像太大,网站很快陷入困境。有些用户在上传图片之前不知道如何调整图片大小,我也不想手动调整图片大小 有没有办法为上传的图像设置最大宽度和高度?我甚至不想把原件留在网站上。我希望网站上最大版本的图像与我设置的宽度和高度限制相匹配。那么为什么不创建一个新的图像大小? 并在模板上使用该图像。将此代码添加到主题函数中。php它将用重新调整大小的版本替换原始图像 function replace_uploaded_image($

我创建了一个博客,一些用户可以通过Wordpress仪表板上传图片。由于原始图像太大,网站很快陷入困境。有些用户在上传图片之前不知道如何调整图片大小,我也不想手动调整图片大小


有没有办法为上传的图像设置最大宽度和高度?我甚至不想把原件留在网站上。我希望网站上最大版本的图像与我设置的宽度和高度限制相匹配。

那么为什么不创建一个新的图像大小?


并在模板上使用该图像。

将此代码添加到主题函数中。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'];

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

文章来源:

这将适用于新图像上传和旧图像上传,将用户上传的大图像自动替换为管理面板中定义的大图像:


您错过了“我甚至不希望原始图像保留在网站上”部分,因此他需要一个比
add\u image\u size()
更复杂的解决方案,该解决方案将保留服务器上的全尺寸图像,即使它不在任何地方使用。他还要求上传/媒体库限制上传时的图像尺寸,这两个问题都不是这个“答案”所要解决的。这真的应该是一个评论,如果有的话。我不会错过的。他没有说限制媒体上传库的大小。即使他不想上传原始的img,主要的问题是放在模板上的图像太大,导致网站崩溃。所以我的答案是一个简单的解决方案。
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
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;
}