图片|云上悦动

WordPress文章自动内链和自动添加标签

今天给大家一共带来两个代码,一个是可以自动检测文章关键词并生成标签、一个是可以将已有的标签转换成内链

第一个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自动为标签添加内链的代码:

它的用途就是你在写这篇文章的时候,如果添加了标签,它会自动把文章内含有标签的字添加成内链

//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 的文章-大白<a href="https://www.godoublog.com/tag/boke" title="更多关于 博客 的文章-大白博客" target="_blank">博客</a>'))."\"";      $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);

演示:

图片[1]|WordPress文章自动内链和自动添加标签|云上悦动
© 版权声明
THE END
喜欢就支持一下吧
点赞0投币 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容