Wordpress - Delete original image - keep thumbnail?
add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata )
{
$upload_dir = wp_upload_dir();
$full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
$deleted = unlink( $full_image_path );
return $metadata;
}
I foud another solution in the web. It's based on the one accepted here, but it takes it even further.
The one, accepted here, removes the main-image and goes on. The solution I found replaces the original image by the image generated for "large". It just goes on without replacing if this image-resolution is not defined.
This way it is ensured that every script, relying on the original image, will still work as before - for example the thumnail regeneration.
http://www.wprecipes.com/how-to-automatically-use-resized-image-instead-of-originals
EDIT:
@dalbaeb pointed me to an issue written in the comments on the blog-post. I rewrote the code based on the API instead of the solution provided there. It's not that much of a difference, but just to use the same function calls as in the API ;)
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_filename = $image_data['sizes']['large']['file'];
// Do what wordpress does in image_downsize() ... just replace the filenames ;)
$image_basename = wp_basename($uploaded_image_location);
$large_image_location = str_replace($image_basename, $large_image_filename, $uploaded_image_location);
// 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']);
// Check if other size-configurations link to the large-file
foreach($image_data['sizes'] as $size => $sizeData) {
if ($sizeData['file'] === $large_image_filename)
unset($image_data['sizes'][$size]);
}
return $image_data;
}
add_filter('wp_generate_attachment_metadata', 'replace_uploaded_image');
EDIT2:
I had a problem with the code on one client where another size-configuration linked to the large-file. I updated the code accordingly. If you have any kind of problems with it, drop me a mail.