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

很多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 = "<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;
}

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

版权声明:内容由互联网用户贡献,不代表本站立场,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 546541225@qq.com 举报,一经查实,本站将立刻删除。