起因

有网友咨询本站,WordPress搭建的网站图片加载过慢,导致页面整体打开速度也慢不少,链接发来经查看一些图片都300-400KB,这样小水管的服务器打开加载肯定慢了,不过网友了解到WebP格式图片,想把上传的图片自动转为WebP格式,这样图片体积能缩小很多,且图片质量也说的过去,页面打开的速度也能提升。下面先说一下什么是WebP格式和为什么要用要使用WebP格式的图片:

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

1.WebP格式图片是由 Google 推出的一种现代图像格式;

2.用来替代传统的图像格式如 JPEG、PNG、GIF 等;

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

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

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

1.自动识别并将上传的图片jpeg、png、gif格式的图片转换为WebP格式;

2.图像质量为90%(如果要设置其他值,可更改代码中的 $quality = 90,建议值 70-90% );

3.不保留原文件(如果要保留,删除或注释这个代码 @unlink($file_path););

4.增加转换容错,极少图片可能会转换失败,则直接上传原图,很少会出现转换失败。

开启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等插件进行统一管理。

该资源来源于WordPress主站,点击下方按钮前往原文页面获取完整内容:

跳转至 WordPress 主站原文页面

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。