Categories: WordPress

WordPress 给文章中站外链接添加 nofollow 属性

为了 SEO ,优化站外链接, WordPress 给文章中站外链接添加 nofollow 属性 ,做法如下

2025年加油呀!Fighting!

可以安装并启用 Nofollow for external link 插件来实现,也可以将下面代码添加到当前主题下面的 functions.php 文件中,这段代码除了能自动给文章和页面中的站外链接添加 nofollow 属性 rel=”nofollow” ,同时还可以实现站外链接在新窗口打开,即添加 target=”_blank” 属性 ,之前添加过这两个属性的不会重复添加

add_filter( 'the_content', 'cn_nf_url_parse');
 
function cn_nf_url_parse( $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;
}

~~~ 让可睿思 • 飞一会儿~~~

打赏打赏分享分享