Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

As our users regularly upload ~6MB images to use on the website (and aren't too familiar with how to resize them first), WordPress stores the originals as well as resizing them to several different sizes.

I'd like a function or plugin that takes the uploaded image, resizes it down to something more manageable and then replaces the original.

I've seen some functions that delete the original but do not replace it, meaning it is impossible to regenerate the thumbnails at a later date. I need this to be replaced so the user can upload a large image and it is automatically resized down and stored for future resizing if needed.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Add this to the functions.php file in the theme folder. It replaces the original image with the large image set in settings. You might want to setup a new image format and use that as the new original size though.

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');
share|improve this answer
1  
If this solution works, it would be very useful to make a plugin. –  Alexey Oct 15 '12 at 16:13
    
Thanks I will test this out! –  Shaun Oct 26 '12 at 8:05
    
I've just tried this again, and but first I added a new size (called 'fullsize') which was 2048x1536 (twice as big as I need it) and now it is all working, the original images are saved as just twice as big as I need them (which I want to keep for future) instead of many times. Thanks! –  Shaun Feb 6 '13 at 15:28
    
Great stuff, glad it worked out for you! –  Paul Phillips Feb 9 '13 at 9:01
    
This code deleted everything from my functions.php file. I checked in the WP editor and in FTP and the file was empty. Had to restore the file from a backup. :( –  jlg Jan 7 at 16:39
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.