怎么给文章关键词自动添加内链链接?

图片-小T爱分享网

文章内链的重要性,很多做SEO的朋友都应该知道。内部链接结构可以引导权值的传递,提高收录,提升内页排名。本文将说明如何用代码的方式给WordPress博客的文章关键词标签自动添加内链,我们只需要在主题目录下的functions.php文件中添加一段代码就可以实现了。

//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);

嫌麻烦可以看下WP Keyword Link插件,网上找到一篇介绍文

小T爱分享网温馨提示:本文最后更新于2022-07-20 17:12:29,某些文章具有时效性,若内容有错误或已失效,欢迎在下方评论区留言向我们反馈。
© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容