• 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?

Viewing 2 replies - 1 through 2 (of 2 total)
  • if ($webp_path) {
    unlink($file['file']);  // Delete the original image
    $file['file'] = $webp_path;  // Update the file path
    $file['type'] = 'image/webp';
    $file['url'] = str_replace(array('.jpeg', '.jpg', '.png'), '.webp', $file['url']);
    }

    After you create the .webp image, you should delete the original PNG or JPEG image to ensure it doesn’t occupy unnecessary server space. After that, You’d need to adjust the file’s metadata so WordPress knows the file extension has changed.

    The above code snippet should help you out/guide how to exactly update the file metadata, so it should appear under the Media Library.

    Hi,

    Webp is a fairly new image format.
    Not all php installations can handle it.
    I think an additional test is also needed :

    function create_webp($file) {
    
        $checkWebp = gd_info();
    	if( empty($checkWebp['WebP Support']) ){
            return;
        }
    
        // your code
    
    }

    Greetings

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to replace old image with converted webp image in WordPress media library’ is closed to new replies.