做 SEO 的大家都知道如果文章中過多的外鏈會分散了該頁面的權重,這樣是不利於網站排名的。所以網站內頁最好是儘量不要鏈接向外部。但是在某些情況下我們不得不鏈接向外部,那麼該如何處理呢?其實我們可以給外部鏈接加上 nofollow 屬性,對蜘蛛聲明不要爬取這條鏈接。這樣就可以有效的解決權重流失的問題。但是在編輯文章中一條鏈接一條鏈接的加 nofollow 屬性工作量實在太大了,小 V 就來教大家讓 WordPress 給文章中的外鏈自動添加 nofollow 屬性。

  1. add_filter( 'the_content', 'v7v3_seo_wl');
  2. function v7v3_seo_wl( $content ) {
  3.     $regexp = "<as[^>]*href=("??)([^" >]*?)1[^>]*>";
  4. if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
  5.         if( !emptyempty($matches) ) {
  6.             $srcUrl = get_option('siteurl');
  7. for ($i=0; $i < count($matches); $i++)
  8.             {
  9.                 $tag = $matches[$i][0];
  10. $tag2 = $matches[$i][0];
  11.                 $url = $matches[$i][0];
  12.                 $noFollow = '';
  13. $pattern = '/targets*=s*"s*_blanks*"/';
  14.                 preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
  15. if( count($match) < 1 )
  16.                     $noFollow .= ' target="_blank" ';
  17.                 $pattern = '/rels*=s*"s*[n|d]ofollows*"/';
  18. $pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
  19.                 if( count($match) < 1 )
  20. $noFollow .= ' rel="nofollow" ';
  21. $pos = strpos($url,$srcUrl);
  22.                 if ($pos === false) {
  23. $tag = rtrim ($tag,'>');
  24.                     $tag .= $noFollow.'>';
  25. $content = str_replace($tag2,$tag,$content);
  26.                 }
  27.         }
  28. $content = str_replace(']]>', ']]>', $content);
  29.     return $content;
  30. }

將以上代碼加入到當前主題的 functions.php 文件即可實現,換主題的時候記得把這段代碼加到新主題裏噢,不然換主題後文章中的外部鏈接就會變成無 nofollow 屬性的了。