首先介紹下 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」),如果手動添加了這兩個屬性則不自動添加