目录
效果预览
核心功能
- 自动转换:上传JPG/PNG/JPEG图片时自动转为WebP格式,显著提升加载速度
- 智能识别:已为WebP的图片不再重复转换,避免冗余操作
- 批量优化:支持历史图片批量转换,一键优化全站图片
- 单张转换:媒体库支持单张图片单独转换,灵活操作
- 错误修复:内置调色板图片转换报错修复,兼容所有图片类型
- SEO友好:保持图片引用路径不变,不影响搜索引擎收录
第一步:修改主题functions.php文件
文件路径:/wp-content/themes/onenav/functions.php
将以下代码添加到文件末尾:
/**
* WordPress 自动WebP转换系统 - 性能与SEO优化
* 支持格式:JPG、PNG、JPEG,显著提升页面加载速度
* 自动识别WebP图片不再重复转换
*/
// 检查服务器WebP支持
function webp_converter_support_check() {
return wp_image_editor_supports( array( 'mime_type' => 'image/webp' ) );
}
// 检查图片是否为WebP格式
function is_webp_image($file_path) {
$extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
if ($extension === 'webp') {
return true;
}
// 通过MIME类型再次确认
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $file_path);
finfo_close($finfo);
return $mime_type === 'image/webp';
}
// 检查是否支持转换的图片格式
function is_supported_image($file_type, $file_path) {
$supported_types = array('image/jpeg', 'image/jpg', 'image/png');
$supported_extensions = array('jpg', 'jpeg', 'png');
$extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
return in_array($file_type, $supported_types, true) ||
in_array($extension, $supported_extensions, true);
}
// 上传时自动转换为WebP
add_filter('wp_handle_upload', 'auto_convert_to_webp_and_remove_original', 10, 2);
function auto_convert_to_webp_and_remove_original($upload, $context) {
// 仅处理图片上传场景
if ($context !== 'upload') {
return $upload;
}
// 检查服务器WebP支持
if (!webp_converter_support_check()) {
error_log('WebP转换失败:服务器不支持WebP格式');
return $upload;
}
$file_path = $upload['file'];
$file_type = $upload['type'];
// 如果是WebP图片,直接返回
if (is_webp_image($file_path)) {
return $upload;
}
// 仅处理支持的图片类型
if (!is_supported_image($file_type, $file_path)) {
return $upload;
}
// 生成WebP文件路径
$webp_path = pathinfo($file_path, PATHINFO_DIRNAME) . '/' . pathinfo($file_path, PATHINFO_FILENAME) . '.webp';
// 如果WebP文件已存在,直接使用
if (file_exists($webp_path)) {
$upload['file'] = $webp_path;
$upload['url'] = str_replace(basename($upload['url']), basename($webp_path), $upload['url']);
$upload['type'] = 'image/webp';
return $upload;
}
// 使用WordPress图片编辑器处理转换
$image_editor = wp_get_image_editor($file_path);
if (is_wp_error($image_editor)) {
error_log('WebP转换失败:' . $image_editor->get_error_message());
return $upload;
}
// 设置压缩质量(SEO优化:平衡质量与文件大小)
$compression_quality = apply_filters('webp_compression_quality', 82);
$image_editor->set_quality($compression_quality);
// 保存为WebP格式
$save_result = $image_editor->save($webp_path, 'image/webp');
if (is_wp_error($save_result)) {
error_log('WebP保存失败:' . $save_result->get_error_message());
return $upload;
}
// 验证WebP文件完整性
if (!file_exists($webp_path) || filesize($webp_path) === 0) {
error_log('WebP转换失败:文件未生成或为空 - ' . $webp_path);
return $upload;
}
// 删除原文件(节省存储空间)
if (file_exists($file_path)) {
@chmod($file_path, 0644);
if (!@unlink($file_path)) {
error_log('无法删除原文件:' . $file_path);
// 如果删除失败,我们仍然使用WebP文件,但不删除原文件
}
}
// 更新上传结果为WebP文件信息
$upload['file'] = $webp_path;
$upload['url'] = str_replace(basename($upload['url']), basename($webp_path), $upload['url']);
$upload['type'] = 'image/webp';
return $upload;
}
// 更新媒体库元数据
add_filter('wp_generate_attachment_metadata', 'update_webp_attachment_metadata', 10, 2);
function update_webp_attachment_metadata($metadata, $attachment_id) {
$file_path = get_attached_file($attachment_id);
if (!is_webp_image($file_path)) {
return $metadata;
}
// 更新缩略图信息为WebP格式
if (!empty($metadata['sizes'])) {
foreach ($metadata['sizes'] as $size => $size_data) {
$original_thumb_path = pathinfo($size_data['file'], PATHINFO_DIRNAME) . '/' . pathinfo($size_data['file'], PATHINFO_FILENAME);
$metadata['sizes'][$size]['file'] = $original_thumb_path . '.webp';
}
}
return $metadata;
}
// 允许WordPress识别WebP文件
add_filter('upload_mimes', 'allow_webp_upload_mime_type');
function allow_webp_upload_mime_type($mimes) {
$mimes['webp'] = 'image/webp';
return $mimes;
}
// 批量转换历史图片
add_action('admin_post_convert_existing_images', 'batch_convert_existing_images');
function batch_convert_existing_images() {
// 安全验证
check_admin_referer('webp_batch_convert_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_die('无权限执行此操作');
}
if (!webp_converter_support_check()) {
wp_die('服务器不支持WebP格式');
}
// 查询所有未转换的图片附件
$args = array(
'post_type' => 'attachment',
'post_mime_type' => array('image/jpeg', 'image/png', 'image/jpg'),
'posts_per_page' => -1,
'post_status' => 'inherit',
);
$attachments = get_posts($args);
$converted_count = 0;
$skipped_count = 0;
$error_count = 0;
foreach ($attachments as $attachment) {
$original_path = get_attached_file($attachment->ID);
// 检查文件是否存在
if (!$original_path || !file_exists($original_path)) {
$error_count++;
continue;
}
// 如果已经是WebP格式,跳过
if (is_webp_image($original_path)) {
$skipped_count++;
continue;
}
$webp_path = pathinfo($original_path, PATHINFO_DIRNAME) . '/' . pathinfo($original_path, PATHINFO_FILENAME) . '.webp';
// 如果WebP文件已存在,跳过
if (file_exists($webp_path)) {
$skipped_count++;
continue;
}
$image_editor = wp_get_image_editor($original_path);
if (is_wp_error($image_editor)) {
$error_count++;
continue;
}
$image_editor->set_quality(85);
$save_result = $image_editor->save($webp_path, 'image/webp');
if (!is_wp_error($save_result) && file_exists($webp_path) && filesize($webp_path) > 0) {
// 更新主文件引用
update_post_meta($attachment->ID, '_wp_attached_file', str_replace(wp_upload_dir()['basedir'], '', $webp_path));
// 删除原文件
if (file_exists($original_path)) {
@chmod($original_path, 0644);
@unlink($original_path);
}
// 更新元数据
$metadata = wp_generate_attachment_metadata($attachment->ID, $webp_path);
wp_update_attachment_metadata($attachment->ID, $metadata);
$converted_count++;
} else {
$error_count++;
// 清理失败的WebP文件
if (file_exists($webp_path)) {
@unlink($webp_path);
}
}
}
wp_redirect(admin_url('upload.php?webp_convert=success&converted=' . $converted_count . '&skipped=' . $skipped_count . '&errors=' . $error_count));
exit;
}
// 在媒体库添加批量转换按钮
add_action('admin_notices', 'add_webp_batch_convert_button');
function add_webp_batch_convert_button() {
if (!current_user_can('manage_options') || get_current_screen()->id !== 'upload') {
return;
}
if (isset($_GET['webp_convert']) && $_GET['webp_convert'] === 'success') {
$converted = isset($_GET['converted']) ? intval($_GET['converted']) : 0;
$skipped = isset($_GET['skipped']) ? intval($_GET['skipped']) : 0;
$errors = isset($_GET['errors']) ? intval($_GET['errors']) : 0;
echo '
‘; echo ‘🚀 WebP转换完成!
‘; echo ‘✅ 成功转换: ‘ . $converted . ‘ 张图片
‘; echo ‘⏭️ 已跳过: ‘ . $skipped . ‘ 张WebP图片
‘; if ($errors > 0) { echo ‘❌ 转换失败: ‘ . $errors . ‘ 张图片’; } echo ‘
‘; } ?>
🚀 图片性能优化 – 将图片转换为WebP格式可显著提升网站加载速度
第二步:创建MU插件修复文件
文件路径:/wp-content/mu-plugins/fix-webp-palette.php(若mu-plugins目录不存在,需先创建)
创建文件后,复制以下代码添加进去:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...
添加小工具
晋公网安备14082402000183号