wordpress给文章中的链接自动添加nofollow属性

我们只需要在当前主题的functions.php文件中添加以下代码就能实现这个功能,内容如下:

//自动给文章的外部链接添加nofollow属性
add_filter('the_content', 'nofollow_cat_posts'); //nofollow文章内容的链接
add_filter('comment_text', 'nofollow_cat_posts'); //nofollow评论内容的链接
 
function nofollow_cat_posts($text) {
global $post;
 if( in_category(1) ) { // 修改这里的分类ID
 $text = stripslashes(wp_rel_nofollow($text));
 }
 return $text;
}

bug:此方法会过了掉文章内容中的反斜杠“\”,去掉stripslashes()函数同样会去掉“\”且部分内容错乱。