/**
* 上传图片自动转为WebP格式
*/add_filter('wp_handle_upload','wpturbo_handle_upload_convert_to_webp');functionwpturbo_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');// 检查转换是否成功且文件大小不为0if(!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;}