文章目录
本文最后更新于 2024-11-04,已超过 365 天未更新,内容可能已失效。

废话不多说,wordpress媒体库上传图片自动转换webp格式,很多伙伴想要这个功能,代码就可以实现。而且可以修改转换后压缩大小比。

教程开始:

添加下面代码在主题functions.php文件中即可,就可以实现媒体库上传图片自动转换webp格式的图片功能

 

[rihide]

add_filter('wp_handle_upload_prefilter', 'webp_handle_upload_prefilter');
add_action('wp_handle_upload', 'webp_convert_image');

function webp_handle_upload_prefilter($file) {
    // 仅对图像文件进行处理
    if (strpos($file['type'], 'image/') === 0) {
        // 添加过滤器以处理上传后的文件
        add_filter('wp_handle_upload', 'webp_convert_image', 10, 2);
    }
    return $file;
}

function webp_convert_image($uploaded_file, $context) {
    // 获取上传文件的路径
    $file_path = $uploaded_file['file'];
    $file_info = pathinfo($file_path);
    $webp_path = $file_info['dirname'] . '/' . $file_info['filename'] . '.webp';

    // 检查文件类型并进行转换
    if (extension_loaded('gd') && in_array($file_info['extension'], ['jpg', 'jpeg', 'png'])) {
        // 加载图像
        if ($file_info['extension'] === 'jpg' || $file_info['extension'] === 'jpeg') {
            $image = imagecreatefromjpeg($file_path);
        } elseif ($file_info['extension'] === 'png') {
            $image = imagecreatefrompng($file_path);
        }

        // 处理透明度(对PNG文件)
        if ($file_info['extension'] === 'png') {
            imagealphablending($image, false);
            imagesavealpha($image, true);
        }

        // 保存为 WebP 格式,100 表示无损压缩
        imagepalettetotruecolor($image);
        imagewebp($image, $webp_path, 60);
        imagedestroy($image);

        // 更新上传信息以包含 WebP 文件
        $uploaded_file['file'] = $webp_path;
        $uploaded_file['type'] = 'image/webp';
    }

    return $uploaded_file;
}

[/rihide]

CC 许可协议
署名-非商业性使用-相同方式共享 4.0 国际 了解协议
文章链接:https://zptheme.com/7292.html
本文作者:子佩·来源:子佩工作室

除非注明,子佩工作室 文章均为原创,转载请以链接形式标明本文地址。

相关推荐

登录后即可发表评论

社交账号登录

全部评论 (0)