wordpress 自动内链标签及自动内链关键字

一、标签自动链接

将以下代码添加到当前主题的functions.php文件中保存:

  1. /* 自动为文章内的标签添加内链开始 */
  2. $match_num_from = 1; //一篇文章中同一个标签少于几次不自动链接
  3. $match_num_to = 1; //一篇文章中同一个标签最多自动链接几次
  4. function tag_sort($a, $b){
  5. if ( $a->name == $b->name ) return 0;
  6. return ( strlen($a->name) > strlen($b->name) ) ? - 1 : 1;
  7. }
  8. function tag_link($content){
  9. global $match_num_from,$match_num_to;
  10. $posttags = get_the_tags();
  11. if ($posttags) {
  12. usort($posttags, "tag_sort");
  13. foreach($posttags as $tag) {
  14. $link = get_tag_link($tag->term_id);
  15. $keyword = $tag->name;
  16. $cleankeyword = stripslashes($keyword);
  17. $url = "<a href=\"$link\" title=\"".str_replace( '%s',addcslashes($cleankeyword, '$'),__( 'View all posts in %s')). "\"";
  18. $url .= ' target="_blank"';
  19. $url .= ">".addcslashes($cleankeyword, '$'). "</a>";
  20. $limit = rand($match_num_from,$match_num_to);
  21. $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word. ')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
  22. $content = preg_replace( '|(<img)(.*?)('.$ex_word. ')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
  23. $cleankeyword = preg_quote($cleankeyword, '\'');
  24. $regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
  25. $content = preg_replace($regEx,$url,$content,$limit);
  26. $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
  27. }
  28. }
  29. return $content;
  30. }
  31. add_filter( 'the_content', 'tag_link', 1);
  32. /* 自动为文章内的标签添加内链结束 *
  33. ————————————————
  34. 版权声明:本文为CSDN博主「youcijibi」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
  35. 原文链接:https://blog.csdn.net/youcijibi/article/details/78363078

代码中注释的很清楚,可以自行改正。

二、指定关键词自动内链

将以下代码添加到当前主题的functions.php文件中保存:

  1. /* 文章指定关键词添加内链开始 */
  2. function replace_text_wps($text){
  3. $replace = array(
  4. '余斗余斗' => '<a href="http://www.yudouyudou.com/" target="_blank" title="余斗余斗">余斗余斗</a>',
  5. '余斗博客' => '<a href="http://m.yudouyudou.com/" target="_blank" title="余斗博客">余斗博客</a>',
  6. '教程' => '<a href="http://www.yudouyudou.com/jiaochengheji/" target="_blank" title="教程">教程</a>'
  7. );
  8. $text = str_replace(array_keys($replace), $replace, $text);
  9. return $text;
  10. }
  11. add_filter( 'the_content', 'replace_text_wps');
  12. ————————————————
  13. 版权声明:本文为CSDN博主「youcijibi」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
  14. 原文链接:https://blog.csdn.net/youcijibi/article/details/78363078

大家自行把代码中的关键词与链接换成自己的,需要其他关键词复制那一行代码即可,非常方便,这个方法有个缺陷就是不能控制关键词锚文本次数,只要在文章中出现的关键词不管几次都会加上链接

之后,文章中再出现标签对应的文字后,会自动把这个文字生成内部链接,如图。

wordpress 自动内链标签及自动内链关键字

 
AudioNote
  • wordpress
  • 标签

发表评论