首先介紹下 nofollow 屬性,nofollow 是一個 HTML 標籤的屬性值。這個標籤的意義是告訴搜尋引擎"不要追蹤此網頁上的連結或不要追蹤此特定連結,簡單的說,新增 nofollow 的部分內容不參與網站排名,便於集中網站權重。
將以下程式碼新增到當前使用主題的 functions.php 檔案中即可。

程式碼預覽

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

以上程式碼意思是,自動給外鏈自動新增 nofollow 屬性 (rel=」nofollow」) 和新視窗開啟屬性 (target=」_blank」),如果手動新增了這兩個屬性則不自動新增