本站使用阿里云的 OSS 存储图片,阿里云 OSS 提供了图片处理服务,通过此服务,可以对存储在阿里云 OSS 中的图鉴进行方法的调整,例如图片质量、图片格式等。
由于使用了阿里云的 CDN 对 OSS 中的图片进行加速处理,图片越大,流量费越高。于是,我希望
- 不改变 OSS 中存储的原始图片(以后可能还要做其他用处)
- 可以提供 webp 格式的图片,减少图片体积,节省 CDN 流量,省钱
- 操作最好是自动化的,不要太麻烦
- 不能改变存储在数据库中的图片链接,降低后续操作难度
- 阿里云格式转换:详情
流程图

效果
在文章编辑器中插入测试内容:
<img src="https://www.npc.ink/01.png">
<img src='https://www.npc.ink/02.jpg?w=800'>
<img src="https://www.npc.ink/exist.png!npcink.webp">
输出时会自动转换为:
<img src="https://www.npc.ink/01.png!npcink.webp">
<img src="https://www.npc.ink/02.jpg!npcink.webp?w=800">
<img src="https://www.npc.ink/exist.png!npcink.webp"> <!-- 已存在的不会被修改 -->
实现步骤
通过 WordPress 的 the_content
过滤器来实现这个需求。这里提供完整方案:
// 在 functions.php 中添加如下代码
function npcink_append_webp_to_images($content) {
// 匹配所有图片链接的正则表达式
$pattern = '/<img[^>]*src=(["\'])(?<url>https?:\/\/[^"\']+?\.(?:png|jpe?g|gif|webp))(?!\!npcink)(\?[^"\']*)?\1/';
$content = preg_replace_callback($pattern, function($matches) {
$original_url = $matches['url'];
$query = $matches[3] ?? ''; // 保留原始查询参数
$separator = (strpos($original_url, '?') === false) ? '?' : '&';
return str_replace(
$matches[0],
'<img src="' . $original_url . '!npcink.webp' . $query . '"',
$matches[0]
);
}, $content);
return $content;
}
add_filter('the_content', 'npcink_append_webp_to_images', 20);
仅替换指定域名的图片
这里,仅处理 n.getimg.net
下的图片链接,其他图片不动
// 在 functions.php 中添加如下代码
//仅针对指定域名-n.getimg.net,在展示文章时做替换
function npcink_specific_domain_webp($content) {
$pattern = '/<img[^>]*src=(["\'])(?<url>https?:\/\/(?:[a-z0-9-]+\.)?n\.getimg\.net[^"\']*?\.(?:png|jpe?g|gif|webp|bmp))(?!(?:[^"\']*?[&?])npcink)(\?[^"\']*)?\1/i';
$content = preg_replace_callback($pattern, function($matches) {
$original_url = $matches['url'];
// 七层防御重复检测
if (strpos($original_url, '!npcink.webp') !== false ||
preg_match('/\.webp(?=\?|$)/i', $original_url)) {
return $matches[0];
}
// 智能拼接策略
$separator = (strpos($original_url, '?') !== false) ? '&' : '!';
return str_replace(
$matches['url'],
$original_url . $separator . 'npcink.webp',
$matches[0]
);
}, $content);
return $content;
}
add_filter('the_content', 'npcink_specific_domain_webp', 20);
结语
通过上述方法,实现了,存储在媒体库中的图片链接是正常的,例如下面这样,方便查看原始图片
<img src="https://n.getimg.net/www/2025/05/d2b5ca33bd970f64a6301fa75ae2eb22.png">
而在文章中展示时,图片链接被上述功能函数,结合阿里云 OSS 处理成这样了,压缩了图片体积,降低了成本
<img src="https://n.getimg.net/www/2025/05/d2b5ca33bd970f64a6301fa75ae2eb22.png!npcink.webp">