#教程# – WordPress文章自动添加内链代码(跳过标题、超链接、表格)特别版

前言

网上有很多WordPress自动添加 TAG 内链代码的教程,但都不会自动跳过 H1-H4 的标题,给标题加上内链感觉特别别扭,这里就给出修改后的特别版。

图片[1] - #教程# – WordPress文章自动添加内链代码(跳过标题、超链接、表格)特别版 - 云线路

教程

添加到主题的 functions.php 文件里即可实现WordPress文章自动添加 TAG 内链代码,并自动跳过标题、超链接、表格

/* 自动为文章标签加 TAG 标签并跳过跳过标题、超链接、表格添加内链 */
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){
  $posttags = get_the_tags();
  $match_num_from = 1;  // 一个标签在文章中出现少于多少次不添加链接
  $match_num_to = 1; // 一篇文章中同一个标签添加几次链接

  if ($posttags) {
      usort($posttags, "tag_sort");
      //var_dump($posttags);
      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, '$'),__('【查看含有[%s]标签的文章】'))."\"";
          $url .= ' target="_blank" ';
          $url .= ">".addcslashes($cleankeyword, '$')."</a>";
          $limit = rand($match_num_from,$match_num_to);
          //不链接的代码
          $pattern = "/<code.*?>(.*?)<\/code>/is"; // 匹配 <code> 标签
          $content = preg_replace_callback(
              $pattern, 
              static function($matches) use ($cleankeyword) {
                  return str_replace($cleankeyword, '%&&&&&%', $matches[0]);
              }, 
              $content
          );
          $title_pattern = "/<(h[1-6]).*?>(.*?)<\/\\1>/is";
          $content = preg_replace_callback(
              $title_pattern, 
              static function($matches) use ($cleankeyword) {
                  return str_replace($cleankeyword, '%&&&&&%', $matches[0]);
              }, 
              $content
          );
          //$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($cleankeyword), $content);
      }
  }
  return $content;
}

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

结语

特别版使用了一个新的正则表达式来跳过标题、超链接、表格添加 TAG 标签内链,同时也避免了在标题和链接中重复添加 TAG 标签内链。

© 本站文章随意转载,但请注明出处!
THE END
点赞10 分享
评论 抢沙发
头像
务必使用真实的邮箱地址评论,虚假邮箱的评论将不通过审核及无回复。
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容