Forcing WordPress to create image resizes only when they are actually needed, saving you tons of space. https://www.wpthemedetector.com/how-to-improve-wordpress-image-functionality/
add_filter( 'image_downsize', 'ml_media_downsize', 10, 3 );
function ml_media_downsize( $out, $id, $size ) {
$dims = null;
$crop = false;
if( is_array( $size ) ) {
// don't handle these for now. but if you want on-the-fly sizes, comment out
// the return statement
return false;
$dims = $size;
// create custom image size name consisting of widthXheight
$size = sprintf( "%dx%d", $size[0], $size[1] );
}
// If image size exists let WP serve it like normally
$imagedata = wp_get_attachment_metadata( $id );
if ( is_array( $imagedata ) && isset( $imagedata['sizes'][$size] ) )
return false;
// Check that the requested size exists, or abort
if ( $dims === null ){
global $_wp_additional_image_sizes;
if ( !isset( $_wp_additional_image_sizes[$size] ) )
return false;
}
// Make the new thumb
if( $dims ){
// we got passed custom width/height as array...
if ( !$resized = image_make_intermediate_size(
get_attached_file( $id ),
$dims[0],
$dims[1],
$crop ) ) {
return false;
}
} else {
if ( !$resized = image_make_intermediate_size(
get_attached_file( $id ),
$_wp_additional_image_sizes[$size]['width'],
$_wp_additional_image_sizes[$size]['height'],
$_wp_additional_image_sizes[$size]['crop'] ) ) {
return false;
}
}
// Save image meta, or WP can't see that the thumb exists now
$imagedata['sizes'][$size] = $resized;
wp_update_attachment_metadata( $id, $imagedata );
// Return the array for displaying the resized image
$att_url = wp_get_attachment_url( $id );
return array( dirname( $att_url ) . '/' . $resized['file'], $resized['width'], $resized['height'], true );
}
add_filter('intermediate_image_sizes_advanced', 'ml_media_prevent_resize_on_upload');
function ml_media_prevent_resize_on_upload( $sizes ) {
// Removing these defaults might cause problems, so we don't, though you could
// probably set them to all be the same dimensions and rely on custom image sizes
// for everything else
return array(
'thumbnail' => $sizes['thumbnail'],
'medium' => $sizes['medium'],
'large' => $sizes['large']
);
}