在搜索引擎优化(SEO)领域,正确使用nofollow属性对于提升网站权重和排名至关重要。本文将详细介绍nofollow属性的定义、作用以及如何通过代码实现自动为外链添加nofollow属性和新窗口打开功能。

换行标签
空格标签 

nofollow是一个HTML标签的属性值,其主要功能是告诉搜索引擎不要追踪此网页上的链接或特定链接。这样做的好处是可以集中网站的权重,避免分散到外部链接上,从而提高核心页面的排名。

为了实现这一功能,您可以通过以下代码自动为文章页面中的外链添加nofollow属性和新窗口打开功能。只需将代码添加到当前使用的主题的functions.php文件中即可。


// 文章页面外链自动添加nofollow属性和新窗口打开
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_nf_url_parse( $content ) {
    $regexp = "]*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(rel=”nofollow”)和新窗口打开(target=”_blank”)。如果某个链接已经手动添加了这两个属性,则代码不会重复添加。

通过这种方式,您可以有效管理网站中的外链,确保搜索引擎将更多权重分配给您的内部页面,从而提升整体SEO效果。同时,新窗口打开的功能也能提升用户体验,让用户在访问外链时不会离开您的网站。

希望这篇文章能帮助您更好地理解nofollow属性及其在SEO中的应用!