wordpress通过代码免插件实现tag标签超链

本来是想用插件的,看了以前常用的一款WP keyword Link Plugin插件,但是已经好久没更新了,国外的吧又一堆英文,本着少用插件,能不用插件就不用的策略,所以准备还是无插件实现。

为什么要添加超链

提高用户体验:通过合理设置超链,读者可以快速了解相关信息,提高阅读效率。

提高搜索引擎排名:搜索引擎会根据网站内外部链接数量、质量等因素来判断网站的权重和排名。

提高文章质量:超链可以让文章内容更加完整、深入,为读者提供更多有价值的信息

便于搜索引擎的索引和爬虫的抓取,提高网站的SEO优化效果

代码

/*Wordpress文章关键词自动添加内链链接代码
*/
//连接数量
 $match_num_from = 1; //一个关键字少于多少不替换
 $match_num_to = 1; //一个关键字最多替换次数
 //连接到WordPress的模块
 add_filter('the_content','tag_link',1);
 //按长度排序
 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){
 global $match_num_from,$match_num_to;
 $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[^>]+>)(.*)('.$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($ex_word), $content);
 }
 }
 return $content; 
 }

以上代码添加至主题Functions.php文件中即可

阅读剩余
提示:本文最后更新于2023年12月18日,如有错误或者已经失效,请留言告知。PS:动动您的小手,帮夏末点一下下方搜索吧
百度一下
关键词不能为空
THE END