🌐
经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用
点我优惠购买
🚀
拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多
点我优惠购买
🛡️
稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少
点我优惠购买
起因
有网友咨询本站,wordpress搭建的网站图片加载过慢,导致页面整体打开速度也慢不少,链接发来经查看一些图片都300-4.0KB,这样小水管的服务器打开加载肯定慢了,不过网友了解到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等插件进行统一管理。
文章版权声明:除非注明,否则均为AI虎哥的工具库原创文章,转载或复制请以超链接形式并注明出处。



还没有评论,来说两句吧...