Automatically replace uploaded image with smaller one in WordPress

Found this here
And the other tip here

This is a lifesaver (or at least, disk space saver) when you have users who upload pictures directly from their digital cameras which are several megs in size.

Paste this into your functions.php file.

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

This might cause WordPress to yell something about add_filter not being defined. This is caused by plugin.php being loaded after functions.php, simply change this by changing

require( ABSPATH . WPINC . '/functions.php' );
require( ABSPATH . WPINC . '/plugin.php' );

into

require( ABSPATH . WPINC . '/plugin.php' );
require( ABSPATH . WPINC . '/functions.php' );

in wp-settings.php.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>