首先介紹下 nofollow 屬性,nofollow 是一個 HTML 標籤的屬性值。這個標籤的意義是告訴搜尋引擎"不要追蹤此網頁上的連結或不要追蹤此特定連結,簡單的說,新增 nofollow 的部分內容不參與網站排名,便於集中網站權重。
將以下程式碼新增到當前使用主題的 functions.php 檔案中即可。
程式碼預覽
-
// 文章頁面外鏈自動新增 nofollow 屬性和新視窗開啟 -
add_filter( 'the_content', 'cn_nf_url_parse');
-
function cn_nf_url_parse( $content ) {
-
$regexp = "<as[^>]*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 = '/targets*=s*"s*_blanks*"/';
-
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
-
if( count($match) < 1 )
-
$noFollow .= ' target="_blank" ';
-
$pattern = '/rels*=s*"s*[n|d]ofollows*"/';
-
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」),如果手動新增了這兩個屬性則不自動新增