2012年4月26日星期四

wordpress无插件实现tag关键词内链

 
 

satan 通过 Google 阅读器发送给您的内容:

 
 

于 12-4-26 通过 averiany涂鸦馆 作者:averainy

以前我的blog用的插件是wp-keyword-link来实现自动内链,但是目前我这里貌似不能使用,也由于插件使用太多造成服务器负担,所以还是减负啦,然后google半天终于算是找到了wordpress无插件实现tag关键词内链的代码,不是不想写,而是我目前还没有兴趣去学php,只能借用别人写好的自己拿来用咯,别的不多说了,直接给代码:

//连接数量  $match_num_from = 1;  //一篇文章中同一个关键字少于多少不秒文本(这个直接填1就好了)  $match_num_to = 10; //一篇文章中同一个关键字最多出现多少次描文本(建议不超过2次)  //连接到WordPress的模块  add_filter('the_content','tag_link',1);  //按长度排序  function tag_sort($a, $b){  	if ( $a->name == $b->name ) return 0;  	return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;  }  //改变标签关键字  function tag_link($content){  global $match_num_from,$match_num_to;  	 $posttags = get_the_tags();  	 if ($posttags) {  		 usort($posttags, "tag_sort");  		 foreach($posttags as $tag) {  			 $link = get_tag_link($tag->term_id);  			 $keyword = $tag->name;  			 //连接代码  			 $cleankeyword = stripslashes($keyword);  			 $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('View all posts in %s'))."\"";  			 $url .= ' target="_blank"';  			 $url .= ">".addcslashes($cleankeyword, '$')."</a>";  			 $limit = rand($match_num_from,$match_num_to);     			//不连接的 代码               $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);  			 $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);     				$cleankeyword = preg_quote($cleankeyword,'\'');     					$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;     				$content = preg_replace($regEx,$url,$content,$limit);     	$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);     		 }  	 }      return $content;  }

将上面的代码添加到wordpress主题中的functions.php这个文件中,保存就ok了,效果跟我这里的一样,

添加之前记得备份哦.


本文作者:averainy | 本文地址: 固定链接 | 我的腾讯微博|我的google+
本站文章除特殊标明者外均为原创,版权所有,如需转载,请以超链接形式注明作者和原始出处及本声明

相关日志


 
 

可从此处完成的操作:

 
 

没有评论:

发表评论