子比主题美化 – 网站文章自动内链和自动添加标签

子比主题美化 – 网站文章自动内链和自动添加标签

在WordPress网站中,通过纯代码实现自动为文章󠄹󠅀󠄪󠄣󠄦󠄞󠄤󠄤󠄞󠄡󠄣󠄨󠄞󠄨󠄡󠅬󠅅󠅃󠄵󠅂󠄪󠄥󠄠󠄠󠅬󠅄󠄹󠄽󠄵󠄪󠄢󠄠󠄢󠄥󠄝󠄠󠄨󠄝󠄡󠄧󠄐󠄡󠄣󠄪󠄢󠄣󠄪󠄤󠄥󠅬󠇕󠆒󠆘󠇖󠆈󠆏󠇕󠅽󠆊󠇕󠆞󠆒󠄐󠇗󠅹󠅸󠇖󠆍󠅳󠇖󠅹󠅰󠇖󠆌󠅹生成标签并添加内链是一种高效且节省时间的SEO优化方法

使用教程

本文代码均为添加到子比主题目录中functions.php或者func.php中

文章自动添加标签

在WordPress中,实现文章发布时自动检测关键字并将其转换为标签的功能,确实可以在后台发布文章时生效。

add_action('save_post', 'auto_add_tags');
function auto_add_tags()
{
    $tags         = get_tags(array('hide_empty' => false));
    $post_id      = get_the_ID();
    $post_content = get_post($post_id)->post_content;
    if ($tags) {
        foreach ($tags as $tag) {
            // 如果文章内容出现了已使用过的标签,自动添加这些标签
            if (strpos($post_content, $tag->name) !== false) {
                wp_set_post_tags($post_id, $tag->name, true);
            }

        }
    }
}

自动为标签添加内链

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

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容