做 SEO 的大家都知道如果文章中過多的外鏈會分散了該頁面的權重,這樣是不利於網站排名的。所以網站內頁最好是儘量不要連結向外部。但是在某些情況下我們不得不連結向外部,那麼該如何處理呢?其實我們可以給外部連結加上 nofollow 屬性,對蜘蛛宣告不要爬取這條連結。這樣就可以有效的解決權重流失的問題。但是在編輯文章中一條連結一條連結的加 nofollow 屬性工作量實在太大了,小編就來教大家讓 WordPress 給文章中的外鏈自動新增 nofollow 屬性。
add_filter( 'the_content', 'wxd_seo_wl');
function wxd_seo_wl( $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;
}
將以上程式碼加入到當前主題的 functions.php 檔案即可實現,換主題的時候記得把這段程式碼加到新主題裡噢,不然換主題後文章中的外部連結就會變成無 nofollow 屬性的了。