当前位置:首页 > CMS教程 > WordPress > 列表

自动给WordPress文章或评论内容的站外链接添加Nofollow属性

发布:smiling 来源: PHP粉丝网  添加日期:2014-04-23 09:28:55 浏览: 评论:0 

出于SEO方面的考虑,对于文章或评论内容的站外链接,不少人都希望自动添加nofollow属性,直接将下面的代码添加到主题的 functions.php 文件即可:

  1. add_filter('the_content', 'auto_nofollow'); //nofollow文章内容的站外链接 
  2.  
  3. add_filter('comment_text', 'auto_nofollow'); //nofollow评论内容的站外链接 
  4.  
  5. function auto_nofollow($content) { 
  6.     //return stripslashes(wp_rel_nofollow($content)); 
  7.  
  8.     return preg_replace_callback('/]+/', 'auto_nofollow_callback', $content); 
  9. } 
  10. function auto_nofollow_callback($matches) { 
  11.     $link = $matches[0]; 
  12.     $site_link = get_bloginfo('url'); 
  13.  
  14.     if (strpos($link, 'rel') === false) { 
  15.         $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link); 
  16.     } elseif (preg_match("%href=S(?!$site_link)%i", $link)) { 
  17.         $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link); 
  18.     } 
  19.     return $link; 
  20. } 

代码中的第1、3行分别是针对文章内容、评论内容的,请根据自己的需要选择,比如不需要自动给文章内容的站外链接添加 nofollow 的话,就注销或删除第一行代码.

Tags: WordPress 评论内容 Nofollow属性

分享到: