
这是一段安全、严谨、无 BUG的 wordpress 函数,作用是:自动把文章内容里的标签文本,转为该标签的归档链接,实现关键词内链,提升 SEO 与用户体验。
一、核心特点
1. 零报错、超稳定
2. 不破坏网页 HTML 结构(最重要)
3. 支持特殊字符标签
4. 不重复添加链接
$limit = 1; // 同一个标签最多添加几次链接(推荐 1)
5. 大小写不敏感
6. 安全防 XSS
7. 只在文章页生效
二、代码
/**
* WordPress 自动为文章标签添加该标签的链接
* 修复版:无报错、正则严谨、不破坏HTML、支持特殊字符、不重复替换
*/
function wpkj_auto_add_tag_link($content) {
// 只在文章内容生效,不影响后台/摘要/页面
if (is_admin() || is_single() === false) {
return $content;
}
$limit = 1; // 同一个标签只添加1次链接
$posttags = get_the_tags();
// 无标签直接返回
if (!$posttags || is_wp_error($posttags)) {
return $content;
}
foreach ($posttags as $tag) {
$name = trim($tag->name);
if (empty($name)) continue;
$link = get_tag_link($tag->term_id);
$title = sprintf(__('View all posts in %s'), esc_attr($name));
// 构建安全的A标签
$replace = '<a target="_blank" href="' . esc_url($link) . '" title="' . $title . '">' . esc_html($name) . '</a>';
// 严谨正则:只替换 纯文本内容,不替换HTML/链接内部
$pattern = '/(?!<[^<>]*>)(' . preg_quote($name, '/') . ')(?![^<>]*<\/a>)/i';
// 执行替换(不区分大小写,只替换前N次)
$content = preg_replace($pattern, $replace, $content, $limit);
}
return $content;
}
add_filter('the_content', 'wpkj_auto_add_tag_link', 10);
