You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress媒体库中用转换后的WebP替换原PNG/JPEG图片

在WordPress中用WebP替换上传的PNG/JPEG图片

可行,只需修改现有钩子函数,在生成WebP后替换WordPress识别的上传文件信息、清理原格式文件,同时确保媒体库元数据记录WebP文件即可。以下是修改后的实现代码:

add_filter( 'wp_handle_upload', 'replace_with_webp' );

function replace_with_webp($file) {
    // 先校验服务器GD库是否支持WebP生成
    if (!function_exists('imagewebp')) {
        return $file;
    }

    $webp_path = '';
    $original_path = $file['file'];

    // 根据原文件类型生成对应WebP
    if ($file['type'] === "image/png") {
        $img = imagecreatefrompng($original_path);
        imagepalettetotruecolor($img);
        imagealphablending($img, true);
        imagesavealpha($img, true);
        $webp_path = str_replace(".png", ".webp", $original_path);
        imagewebp($img, $webp_path, 100);
        imagedestroy($img);
    } elseif ($file['type'] === "image/jpg" || $file['type'] === "image/jpeg") {
        $img = imagecreatefromjpeg($original_path);
        imagepalettetotruecolor($img);
        imagealphablending($img, true);
        imagesavealpha($img, true);
        $webp_path = str_replace(array(".jpg", ".jpeg"), ".webp", $original_path);
        imagewebp($img, $webp_path, 100);
        imagedestroy($img);
    }

    // 仅当WebP文件生成成功时执行替换
    if (!empty($webp_path) && file_exists($webp_path)) {
        // 修改$file核心参数,让WordPress认为上传的是WebP文件
        $file['file'] = $webp_path;
        $file['url'] = str_replace(basename($original_path), basename($webp_path), $file['url']);
        $file['type'] = "image/webp";

        // 删除原格式文件,避免冗余存储
        if (file_exists($original_path)) {
            unlink($original_path);
        }
    }

    return $file;
}

关键修改说明:

  • GD库兼容性校验:提前检查imagewebp函数是否存在,避免服务器不支持WebP时触发报错
  • 生成结果校验:只有WebP文件成功创建后才执行替换逻辑,防止原文件丢失
  • 替换文件识别信息:修改$file数组的本地路径、访问链接、MIME类型,让WordPress后续的媒体库入库、缩略图生成等流程都基于WebP文件处理
  • 清理原文件:生成WebP后删除原PNG/JPEG文件,减少存储空间占用

注意事项:

  1. 确保服务器PHP环境安装了支持WebP的GD库,可通过phpinfo()查看GD扩展配置确认
  2. 测试阶段建议先上传小文件验证逻辑,避免批量操作导致文件丢失
  3. WordPress会自动基于WebP原文件生成对应尺寸的WebP缩略图,无需额外配置

内容的提问来源于stack exchange,提问作者Alex Douglas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:30:51