【wordpress教程】自动为文章标签添加站内链接

屏聚源码 wordpress教程评论201,628阅读模式

  站内链接是站长们在做网站SEO时必须要考虑的问题,而之前给别的网站做网站诊断时,就发现很多站长都不注意这个问题。那么使用wordpress建站的就有福咯!我们可以将下方代码放入相应主题的functions.php中,即可实现自动为文章标签添加站内链接了。像我的网站就是哦。

  当然,对于正常情况这样是行得通的,而且的确有利于站内优化,但是很多时候我们也要自行对一些相似关键词进行添加链接。至于为什么这么做你可以想象为什么。

  1.   $match_num_from = 1; // 一个标签在文章中出现少于多少次不添加链接

  2.   $match_num_to = 1; // 一篇文章中同一个标签添加几次链接

  3.   add_filter('the_content','tag_link',1);

  4.   //按长度排序

  5.   function tag_sort($a, $b){

  6.   if ( $a->name == $b->name ) return 0;

  7.   return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;

  8.   }

  9.   //为符合条件的标签添加链接

  10.   function tag_link($content){

  11.   global $match_num_from,$match_num_to;

  12.   $posttags = get_the_tags();

  13.   if ($posttags) {

  14.   usort($posttags, "tag_sort");

  15.   foreach($posttags as $tag) {

  16.   $link = get_tag_link($tag->term_id);

  17.   $keyword = $tag->name;

  18.   //链接的代码

  19.   $cleankeyword = stripslashes($keyword);

  20.   $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('View all posts in %s'))."\"";

  21.   $url .= ' target="_blank"';

  22.   $url .= ">".addcslashes($cleankeyword, '$')."</a>";

  23.   $limit = rand($match_num_from,$match_num_to);

  24.   //不链接的代码

  25.   $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);

  26.   $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);

  27.   $cleankeyword = preg_quote($cleankeyword,'\'');

  28.   $regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;

  29.   $content = preg_replace($regEx,$url,$content,$limit);

  30.   $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);

  31.   }

  32.   }

  33.   return $content;

  34.   }

继续阅读
屏聚源码
辅助编程工具通义灵码 你的智能编码助手 屏聚学院

辅助编程工具通义灵码 你的智能编码助手

通义灵码是阿里推出的基于通义大模型,提供代码智能生成、研发智能问答能力的人工智能编码助手,经过海量优秀开源代码数据训练,可根据当前代码文件及跨文件的上下文,为你生成行级/函数级代码、单元测试、代码注释...
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定