WordPress文章关键词自动添加内部链接代码

2025年6 月8日 / 网站源码 / 没有评论 / 66次

把下面代码展开复制粘贴到主题目录下的functions.php文件里面就可以了。其中可以修改match_num_from和match_num_to的值,建议把值设置大一点,这样文章内所有同个关键词都能内部链接。

  1. /*Wordpress文章关键词自动添加内链链接代码
  2. */
  3. //连接数量
  4. $match_num_from = 1; //一个关键字少于多少不替换
  5. $match_num_to = 1; //一个关键字最多替换次数
  6. //连接到WordPress的模块
  7. add_filter('the_content','tag_link',1);
  8. //按长度排序
  9. function tag_sort($a$b){
  10. if ( $a->name == $b->name ) return 0;
  11. return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
  12. }
  13. //改变标签关键字
  14. function tag_link($content){
  15. global $match_num_from,$match_num_to;
  16. $posttags = get_the_tags();
  17. if ($posttags) {
  18. usort($posttags"tag_sort");
  19. foreach($posttags as $tag) {
  20. $link = get_tag_link($tag->term_id);
  21. $keyword = $tag->name;
  22. //连接代码
  23. $cleankeyword = stripslashes($keyword);
  24. $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('查看所有文章关于 %s'))."\"";
  25. $url .= 'target="_blank"';
  26. $url .= ">".addcslashes($cleankeyword, '$')."</a>";
  27. $limit = rand($match_num_from,$match_num_to);
  28. //不连接的代码
  29. $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
  30. $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
  31. $cleankeyword = preg_quote($cleankeyword,'\'');
  32. $regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
  33. $content = preg_replace($regEx,$url,$content,$limit);
  34. $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
  35. }
  36. }
  37. return $content;
  38. }