WordPress文章关键词自动添加链接

文章页面的关键词自动添加 超级链接,也就是所谓的内链,主要的是有利于 SEO,有利于读者方便查看所有相关关键词的所有文章,也就是对关键词进行了站内搜索。在主题的 functions.php 文件中添加以下代码:

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

为了防止避免过度 SEO,强烈建议最多替换 2 个重复的词!!

© 版权声明
THE END
喜欢就支持以下吧
点赞0赞赏
分享
相关推荐
  • 暂无相关文章
评论 抢沙发