首页    >    新闻资讯    >   自动调整文章中所上传图片的大小

自动调整文章中所上传图片的大小

下面这个脚本能使WordPress生成一个大幅图片,并用该图片代替用户所上传的图片(如果所上传图片尺寸大于用户的后台设置),以节省服务器空间,如果你链接到的是原始图片的缩略图,还可以节省带宽,效果和lightbox插件一样。

只要将以下代码添加到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'];

 

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

 

注意:不同主题对该代码的支持程度会有所不同

原文:How to automatically use resized images instead of originals

分类:新闻资讯

标签:, , , ,

* 版权声明:作者WordPress啦! 转载请注明出处。