最近在做一個新網站,Google 剛開始收錄的時候發現歸檔頁面的排名比文章還高,猜測原因是歸檔頁面獲得的內鏈太多了,因此產生一個把所有的指向歸檔頁面的連結全部加上 rel=”nofollow” 屬性的想法。

要達到這個目的,我們完全可以用 WordPress 強大的 filter 來實現。開啟主題的 functions.php ,在裡面加上以下的程式碼:

//給標籤雲裡的連結加上 rel="nofollow"
add_filter('wp_tag_cloud', 'cis_nofollow_tag_cloud');
function cis_nofollow_tag_cloud($text) {
return str_replace('<a href='/spanspan,/span%20span'<a rel="nofollow" href='/spanspan,/span %20span$text/spanspan)/spanspan;/span%20br%20/span/spanbr%20/ br%20/span//給%20the_tags()%20 生成的連結%20 加上%20rel="nofollow"/spanbr%20/add_filterspan(/spanspan'the_tags', 'cis_nofollow_the_tag');
function cis_nofollow_the_tag($text) {
return str_replace('rel="tag"', 'rel="tag nofollow"', $text);
}
 
//給 wp_list_categories() 生成的連結加上 rel="nofollow"
add_filter( 'wp_list_categories', 'cis_nofollow_wp_list_categories' );
function cis_nofollow_wp_list_categories( $text ) {
 
$text = stripslashes($text);
$text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
return $text;
}
 
//給 the_category() 生成的連結加上 rel="nofollow"
add_filter( 'the_category', 'cis_nofollow_the_category' );
function cis_nofollow_the_category( $text ) {
 
$text = str_replace('rel="category tag"', "", $text);
$text = cis_nofollow_wp_list_categories($text);
return $text;
}
 
//給 the_author_post_link 生成的連結加上 rel="nofollow"
add_filter('the_author_posts_link', 'cis_nofollow_the_author_posts_link');
function cis_nofollow_the_author_posts_link ($link) {
return str_replace('</a><a href='/spanspan,/span%20span'<a rel="nofollow" href='/spanspan,/span %20span$link/spanspan)/spanspan;/span%20br%20/span/spanbr%20/ br%20/span//給%20comments_popup_link_attributes()%20 生成的連結加上%20rel="nofollow"/spanbr%20/add_filterspan(/spanspan'comments_popup_link_attributes', 'cis_nofollow_comments_popup_link_attributes');
function cis_nofollow_comments_popup_link_attributes () {
echo ' rel="nofollow"';
}

上面的 filter 針對的都是主題開發時一些使用率比較高的函式,基本上已經能滿足我的要求了。