Automatically scales down oversized image uploads to a maximum width and height before WordPress finishes processing them. This helps prevent unnecessarily large files from being stored on the server, reducing disk usage and improving page load times, without requiring an image optimisation plugin.
1. Open your theme’s functions.php file.
2. Add the code above.
3. Save the file.
4. Upload a new image via Media > Add New (or any page that uses the media uploader).
Done — any image wider or taller than 2048px will now be automatically resized down on upload.
function resize_large_uploaded_images( $file ) {
$max_width = 2048;
$max_height = 2048;
$image_path = $file['file'];
$image_size = getimagesize( $image_path );
if ( ! $image_size ) {
return $file;
}
list( $width, $height ) = $image_size;
if ( $width > $max_width || $height > $max_height ) {
$editor = wp_get_image_editor( $image_path );
if ( ! is_wp_error( $editor ) ) {
$editor->resize( $max_width, $max_height, false );
$editor->save( $image_path );
}
}
return $file;
}
add_filter( 'wp_handle_upload', 'resize_large_uploaded_images' );