WordPress外部链接自动添加nofollow标签函数分享

这是一个为WordPress网站设计的函数,能够自动为外部链接添加nofollow标签,有助于减少网站权重流失,提升SEO优化效果。无需手动修改每个链接,也无需额外插件,简单高效。

使用方法:将以下代码添加到主题的Functions.php文件中。

代码功能:
通过正则表达式匹配文章内容中的链接,判断是否为外部链接。如果是外部链接,自动添加rel=”nofollow”和target=”_blank”属性,确保不影响用户体验,同时优化SEO。

// 文章自动添加 nofollow
add_filter('the_content', 'tin_seo_wl');
function tin_seo_wl($content) {
    $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
    if (preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
        if (!empty($matches)) {
            $srcUrl = get_option('siteurl');
            for ($i = 0; $i < count($matches); $i++) {
                $tag = $matches[$i][0];
                $tag2 = $matches[$i][0];
                $url = $matches[$i][0];
                $noFollow = '';
                $pattern = '/target\s*=\s*"\s*_blank\s*"/';
                preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
                if (count($match) < 1) {
                    $noFollow .= ' target="_blank" ';
                }
                $pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
                preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
                if (count($match) < 1) {
                    $noFollow .= ' rel="nofollow" ';
                }
                $pos = strpos($url, $srcUrl);
                if ($pos === false) {
                    $tag = rtrim($tag, '>');
                    $tag .= $noFollow . '>';
                    $content = str_replace($tag2, $tag, $content);
                }
            }
        }
    }
    $content = str_replace(']]>', ']]>', $content);
    return $content;
}

 

注意事项:

  • 代码会跳过站内链接,仅处理外部链接。
  • 添加前建议备份Functions.php文件,以防万一需要恢复。

此函数轻量实用,适合希望提升网站SEO的WordPress用户。

相关阅读

表情
文章目录