WordPress Image Simplification
Published on .
By default image uploads are processed, changing the quality and saving multiple sizes. This is for good reason, because it provides some basic optimization to prevent serving huge images. That said, it uses JPEG and creates lots of files …and for most use cases I think one medium sized WebP image is enough. So… here’s code to do that!
add_filter( 'big_image_size_threshold', '__return_false' );
add_filter( 'intermediate_image_sizes', '__return_empty_array' );
add_filter('wp_handle_upload', 'resize_and_convert_to_webp');
function resize_and_convert_to_webp($file) {
if (strpos($file['type'], 'image/') !== 0) {
return $file;
}
$image_editor = wp_get_image_editor($file['file']);
if (is_wp_error($image_editor)) {
return $file;
}
// Resize the image (adjust dimensions as needed)
$image_editor->resize(1024, null, true);
// Save the resized image as WebP
$webp_path = str_replace(pathinfo($file['file'], PATHINFO_EXTENSION), 'webp', $file['file']);
$image_editor->save($webp_path, 'image/webp');
$file['type'] = 'image/webp';
$file['url'] = str_replace( '.'.pathinfo($file['file'], PATHINFO_EXTENSION), '.webp', $file['url'] );
$file['file'] = $webp_path;
return $file;
}