Alex Douglas
Alex Douglas

Reputation: 576

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:

 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?

Upvotes: 3

Views: 2460

Answers (2)

Николай
Николай

Reputation: 1123

You can go through all images by these code

$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 :)
}

Upvotes: 1

Fajr Yassin
Fajr Yassin

Reputation: 26

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/

Upvotes: -1

Related Questions