wordpress文章,给关键词自动添加链接代码

wordpress文章关键词自动添加链接代码

文章页面的关键词自动添加 超级链接,也就是所谓的内链,主要的是有利于SEO,有利于读者方便查看所有相关关键词的所有文章,也就是对关键词进行了站内搜索。

在主题的functions.php文件中添加以下代码:

具体位置:域名/wp-includes/functions.php

在主题目录下的functions.php文件中添加下方代码就可以实现了WordPress给文章关键词标签自动添加内链。

//WordPress文章关键词自动内链
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){
  $match_num_from = 1;  //一个标签少于几次不链接
  $match_num_to = 1;  //一个标签最多链接几次
  $posttags = get_the_tags();
  if ($posttags) {
    usort($posttags, "tag_sort");
    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);
      //不链接代码
      $content = preg_replace( '|(<a[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</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($ex_word), $content);
    }
  }
  return $content;
}
add_filter('the_content','tag_link',1);

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

👍 若您喜欢,请分享给您的朋友