How to automatically use resized images instead of originals

February 8, 2010 at 8:57 am

This script will replace the uploaded image (if bigger than the larger size defined in your settings) by the large image generated by WordPress to save space in your server, and save bandwidth if you link a thumbnail to the original image, like when a lightbox plugin is used.

Simply paste the following code on your functions.php file and save it. No other action is needed!

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

Thanks to Serge Rauberfor sharing his great tip with us!

Tags: