WordPress网站免插件,上传图片自动转为WebP格式

笔记6天前更新 阿轩
46 0 0
WordPress网站免插件,上传图片自动转为WebP格式

用一段php代码,免插件的方式,实现图片上传WordPress网站,自动将JPEG、PNG、GIF等转换为WebP格式图片,大大提高网站文章编辑的效率。

之前我在写文章的时候,先在笔记软件上写好文章,直接发送到 wordpress,比如思源笔记等,然后在使用插件进行图片压缩,比如Squoosh、TinyPNG,但目前比较适合网站的文件格式已经基本都变成了 webp 格式,即便是通过压缩后的 png 和 jpeg 都不如 webp 的性价比高。

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

WebP格式图片是由 Google 推出的一种现代图像格式,用来替代传统的图像格式如 JPEG、PNG、GIF 等。

相比 JPEG、PNG和GIF,WebP 通常可以提供更小的文件大小,同时保持相似或更好的图像质量。

较小的图片体积让网页加载更快,能够提高用户体验。快速加载的网页对 SEO(搜索引擎优化) 更好,提升网站在 Google、百度 等搜索引擎中的排名。

自动转化WebP代码

代码功能说明:

  • 自动识别并将上传的图片jpeg、png、gif格式的图片转换为WebP格式
  • 图像质量为80%(如果要设置其他值,可更改代码中的 $quality = 80,建议值 70-90% )
  • 不保留原文件(如果要保留,删除或注释这个代码 @unlink($file_path);
/**
 * Convert Uploaded Images to WebP Format with Custom Quality
 */
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 = 80
; // 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');
                if (!is_wp_error($saved_image) && file_exists($saved_image['path'])) {
                    // 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';
                    // Optionally delete the original file
@unlink($file_path);
                }
            }
        }
    }
    return $upload;
}

这里使用Code Snippets、WPCode等插件进行统一管理PHP 函数。

WordPress网站免插件,上传图片自动转为WebP格式

实际测试

上传前格式为PNG,大小为569KB

WordPress网站免插件,上传图片自动转为WebP格式

上传后格式自动为WebP,大小为194KB,变化极其明显

WordPress网站免插件,上传图片自动转为WebP格式
© 版权声明

相关文章

没有相关内容!

暂无评论

none
暂无评论...