[英]How to replace old image with converted webp image in Wordpress media library
I have this hook in Wordpress that will convert any uploaded PNGs or JPEGS to WebP images:我在 Wordpress 中有这个钩子,它将任何上传的 PNG 或 JPEGS 转换为 WebP 图像:
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.所以现在每次我将新图像上传到媒体库时,也会创建一个 .webp 版本。 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.
但是,我想找到一种方法,用新创建的 .webp 图片替换上传到媒体库的旧 PNG 或 JPEG 图片。 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?
所以当我 go 到 Wordpress 中的媒体库时,我会看到 .webp 图像而不是 PNG 或 JPEG 这可能吗?
You can go through all images by these code您可以通过这些代码 go 通过所有图像
$posts = get_posts([
'post_mime_type' => 'image',
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => -1,
]);
foreach ($posts as $post) {
// Here you can compare the file extension
// and, using your code, convert the image (by creating another one)
// and delete the original jpg/png file :)
}
you can use this plugin你可以使用这个插件
HOW DOES THIS WORK?这是如何运作的?
1- If you have just installed the plugin, you can optimize images with one click. 1-如果您刚刚安装了插件,您可以一键优化图像。 Image size will be smaller after generate webp
生成webp后图片尺寸会变小
2- New images that will be added to the Media Library will be converted automatically. 2- 将添加到媒体库的新图像将自动转换。
https://wordpress.org/plugins/webp-converter-for-media/ https://wordpress.org/plugins/webp-converter-for-media/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.