WordPress网站文章页外链nofollow标签和新窗口打开方法

橘子网 3,456

很多WordPress网站文章页外链没有进行优化,如果手动加nofollow标签的话是很麻烦的一件事,所以去互联网查找了一些方法,发现很多代码并不起作用,而且网络东西鱼龙混杂,优质的信息反而不容易找到,下面是解决的代码并记录下来。

//给文章外链添加nofollow
add_filter('the_content','web589_the_content_nofollow',999);
function web589_the_content_nofollow($content){
preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){
foreach($matches[1] as $val){
if( strpos($val,home_url())===false ) $content=str_replace("href="$val"", "href="$val" rel="external nofollow" ",$content);
}
}
return $content;
}
//文章外链nofollow结束

自动新窗口打开并同时添加nofollow的代码:

//出站链接自动添加nofollow和在新窗口打开
add_filter( 'the_content', 'auto_nofollow_for_external_link');
function auto_nofollow_for_external_link( $content ) {
    $regexp = "<as[^>]*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 = '/targets*=s*"s*_blanks*"/';
                preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
                if( count($match) < 1 )
                    $noFollow .= ' target="_blank" ';

                $pattern = '/rels*=s*"s*[n|d]ofollows*"/';
                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;
}

第一种代码较少,比较简洁,如果想同时实现nofollow标签和新窗口代开可以使用第二种方法,当然,如果换了主题,上面的代码要重新安装。对了,上面的代码是要放在主题编辑器functions.php中保存即可使用。

上一篇:

下一篇:

相关阅读

分享