I have this hook in WordPress that will convert any uploaded PNGs or JPEGS to WebP images:
add_filter( 'wp_handle_upload', 'create_webp' );
function create_webp($file) {
if ($file['type'] === "image/png") {
// Create and save
$img = imagecreatefrompng($file['file']);
imagepalettetotruecolor($img);
imagealphablending($img, true);
imagesavealpha($img, true);
imagewebp($img, str_replace(".png" ,".webp", $file['file']), 100);
imagedestroy($img);
}
elseif($file['type'] === "image/jpg" || $file['type'] === "image/jpeg"){
$img = imagecreatefromjpeg($file['file']);
imagepalettetotruecolor($img);
imagealphablending($img, true);
imagesavealpha($img, true);
if($file['type'] === "image/jpg"){
imagewebp($img, str_replace(".jpg" ,".webp", $file['file']), 100);
}
else{
imagewebp($img, str_replace(".jpeg" ,".webp", $file['file']), 100);
}
imagedestroy($img);
}
return $file;
}
So now every time I upload a new image to the media library, a .webp version is also created. However, I would like to find a way to replace the old PNG or JPEG image that was uploaded to the media library with the newly created .webp image. So when I go to the media library in WordPress, I would see the .webp image and not the PNG or JPEG Is this possible?
2
Answers
you can use this plugin
HOW DOES THIS WORK?
1- If you have just installed the plugin, you can optimize images with one click. Image size will be smaller after generate webp
2- New images that will be added to the Media Library will be converted automatically.
https://wordpress.org/plugins/webp-converter-for-media/
You can go through all images by these code