【问题标题】:How to replace old image with converted webp image in Wordpress media library如何在 Wordpress 媒体库中用转换后的 webp 图片替换旧图片
【发布时间】:2022-11-17 18:29:07
【问题描述】:

我在 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;
 }

所以现在每次我将新图像上传到媒体库时,也会创建一个 .webp 版本。但是,我想找到一种方法来用新创建的 .webp 图像替换上传到媒体库的旧 PNG 或 JPEG 图像。因此,当我转到 Wordpress 中的媒体库时,我会看到 .webp 图像,而不是 PNG 或 JPEG 这可能吗?

【问题讨论】:

    标签: php wordpress webp image-conversion


    【解决方案1】:

    您可以通过这些代码浏览所有图像

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

    【讨论】:

      【解决方案2】:

      你可以使用这个插件

      这是如何运作的?

      1-如果您刚刚安装了插件,您可以一键优化图像。生成webp后图片尺寸会变小

      2- 将添加到媒体库的新图像将自动转换。

      https://wordpress.org/plugins/webp-converter-for-media/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-15
        • 2018-12-01
        • 2023-04-07
        • 2014-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多