下面這個腳本能使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/