共計 1488 個字符,預計需要花費 4 分鐘才能閱讀完成。
很多 WordPress 網站文章頁外鏈沒有進行優化,如果手動加 nofollow 標簽的話是很麻煩的一件事,所以去互聯網查找了一些方法,發現很多代碼并不起作用,而且網絡東西魚龍混雜,優質的信息反而不容易找到,下面是解決的代碼并記錄下來。
// 給文章外鏈添加 nofollow
add_filter('the_content','web589_the_content_nofollow',999);
function web589_the_content_nofollow($content){preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){foreach($matches[1] as $val){if( strpos($val,home_url())===false ) $content=str_replace("href="$val"","href="$val" rel="external nofollow" ",$content);
}
}
return $content;
}
// 文章外鏈 nofollow 結束
自動新窗口打開并同時添加 nofollow 的代碼:
// 出站鏈接自動添加 nofollow 和在新窗口打開
add_filter('the_content', 'auto_nofollow_for_external_link');
function auto_nofollow_for_external_link($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 標簽和新窗口代開可以使用第二種方法,當然,如果換了主題,上面的代碼要重新安裝。對了,上面的代碼是要放在主題編輯器 functions.php 中保存即可使用。
正文完