国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > WordPress > WordPress自动调整文章中所上传图片的大小

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

来源:程序员人生   发布时间:2013-11-17 00:53:07 阅读次数:2524次

下面这个脚本能使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

出处:http://www.wordpress.la/

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生