WordPress无插件外部链接自动添加nofollow标签

maolai 网站建设评论125阅读模式

在wordpress写文章时,有时内容会引用或分享一些外部链接地址,有些外部链接是没有加Nofollow标签,在技术层面是有传递出去权重。严格要求的话是需要在外部链接全部加上nofollow标签。如果手动每个链接加入是很麻烦,可以直接找一些wordpress插件安装。当然我们也可以通过代码实现无插件添加方法。

//文章自动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;
}

添加到当前主题Funcions.php 文件中,这样所有的外部链接就会自动加上nofollow标签。当然目前一些wordpress主题设置有这个nofollow标签功能。

 
maolai
  • 本文由 maolai 发表于 2018年6月4日 13:17:06
  • 转载请务必保留本文链接:http://www.bokequ.com/475.html

发表评论