skip to Main Content

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


  1. 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/

    Login or Signup to reply.
  2. 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 :)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search