You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WordPress中含/?的所有动态链接添加rel="nofollow"

WordPress为带/?的动态链接添加rel="nofollow"的解决方案

可以通过在主题的functions.php中添加自定义过滤器来实现,以下是针对不同场景的具体代码:

处理文章/页面内容中的链接

这个过滤器会遍历页面内容里的所有<a>标签,自动为包含/?的URL添加rel="nofollow"属性,同时保留原有rel属性(比如noopener):

function add_nofollow_to_dynamic_links($content) {
    $pattern = '/<a(.*?)href="([^"]+)"(.*?)>/i';
    $replacement = function($matches) {
        $href = $matches[2];
        $attrs = $matches[1] . $matches[3];
        
        // 匹配包含/?的URL,排除根目录单独的/?(可根据需求移除该判断)
        if (strpos($href, '/?') !== false && $href !== '/?') {
            if (preg_match('/rel="([^"]+)"/i', $attrs, $rel_matches)) {
                // 已有rel属性,追加nofollow
                $attrs = str_replace($rel_matches[0], 'rel="' . $rel_matches[1] . ' nofollow"', $attrs);
            } else {
                // 无rel属性,直接添加
                $attrs .= ' rel="nofollow"';
            }
        }
        
        return '<a' . $attrs . ' href="' . $href . '">';
    };
    
    return preg_replace_callback($pattern, $replacement, $content);
}
add_filter('the_content', 'add_nofollow_to_dynamic_links');

处理导航菜单中的链接

如果需要给菜单里的动态链接也添加nofollow,添加以下过滤器:

function add_nofollow_to_menu_dynamic_links($atts, $item, $args) {
    $href = $atts['href'];
    if (strpos($href, '/?') !== false && $href !== '/?') {
        if (isset($atts['rel'])) {
            $atts['rel'] .= ' nofollow';
        } else {
            $atts['rel'] = 'nofollow';
        }
    }
    return $atts;
}
add_filter('nav_menu_link_attributes', 'add_nofollow_to_menu_dynamic_links', 10, 3);

使用说明

  1. 登录WordPress后台,进入外观 → 主题文件编辑器,找到当前主题的functions.php文件
  2. 将上述代码粘贴到文件末尾(建议先备份原文件)
  3. 点击“更新文件”保存更改

注意:如果使用子主题,务必修改子主题的functions.php,避免主题更新时代码被覆盖。

内容的提问来源于stack exchange,提问作者Ryszard Kaczorowski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:07:24