欢迎光临
老陈一直在努力

WordPress免插件实现上传图片自动转为WebP格式

为什么要使用WebP格式的图片

WebP格式图片是由 Google 推出的一种现代图像格式,
用来替代传统的图像格式如 JPEG、PNG、GIF 等。
相比 JPEG、PNG和GIF,WebP 通常可以提供更小的文件大小,同时保持相似或更好的图像质量。
较小的图片体积让网页加载更快,能够提高用户体验。快速加载的网页对 SEO(搜索引擎优化)更好,提升网站在 Google、百度 等搜索引擎中的排名。

自动转化WebP代码功能说明:

自动识别并将上传的图片jpeg、png、gif格式的图片转换为WebP格式
图像质量为90%(如果要设置其他值,可更改代码中的 $quality = 90,建议值 70-90% )
不保留原文件(如果要保留,删除或注释这个代码 @unlink($file_path);)
增加转换容错,极少图片可能会转换失败,则直接上传原图,很少会出现转换失败

开启WordPress上传图片自动转为WebP格式

找到主题文件 function.php 文件,打开后,在最后面添加如下代码:

/**
 * 上传图片自动转为WebP格式
 */
add_filter('wp_handle_upload', 'wpturbo_handle_upload_convert_to_webp');
function wpturbo_handle_upload_convert_to_webp($upload) {
    if (in_array($upload['type'], ['image/jpeg', 'image/png', 'image/gif'])) {
        $file_path = $upload['file'];
        if (extension_loaded('imagick') || extension_loaded('gd')) {
            $image_editor = wp_get_image_editor($file_path);
            if (!is_wp_error($image_editor)) {
                // Set WebP quality (adjust as needed)
                $quality = 90; // Adjust between 0 (low) to 100 (high)
                $image_editor->set_quality($quality); // Set quality for WebP conversion
                $file_info = pathinfo($file_path);
                $dirname = $file_info['dirname'];
                $filename = $file_info['filename'];
                $def_filename = wp_unique_filename($dirname, $filename . '.webp');
                $new_file_path = $dirname . '/' . $def_filename;
                $saved_image = $image_editor->save($new_file_path, 'image/webp');

                // 检查转换是否成功且文件大小不为0
                if (!is_wp_error($saved_image) && file_exists($saved_image['path']) && filesize($saved_image['path']) > 0) {
                    // Update the upload data to use the WebP image
                    $upload['file'] = $saved_image['path'];
                    $upload['url'] = str_replace(basename($upload['url']), basename($saved_image['path']), $upload['url']);
                    $upload['type'] = 'image/webp';
                    // 删除原始文件
                    @unlink($file_path);
                } else {
                    // 如果转换失败或文件为0KB,删除可能创建的无效WebP文件
                    if (file_exists($new_file_path)) {
                        @unlink($new_file_path);
                    }
                    // 保持原始文件不变
                }
            }
        }
    }
    return $upload;
}
注意:WordPress主题更换或升级后,需要再次修改此文件。
建议代码用Code Snippets、WPCode等插件进行统一管理。
赞(0) 打赏
未经允许不得转载:技术宅老陈 » WordPress免插件实现上传图片自动转为WebP格式

评论 抢沙发

文章有用,打赏作者

非常感谢您的打赏,您的鼓励将是老陈的动力!

支付宝扫一扫

微信扫一扫