wordpress 不使用插件让标签TAG内链

本文介绍了如何在WordPress中手动实现TAG内链,避免使用可能导致网站速度下降的插件。通过在主题的Functions.php文件中添加特定代码,可以自动将文章中的TAG标签转化为内链。代码包括设置TAG链接出现的次数限制,并提供了详细的步骤和源代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

wordpress如何实现tag标签内链?网上有人说使用插件。

一开始我也是在网上看到别人推荐,使用的Simple Tags这个插件来完成tag内链的。

但是使用后,效果并不明显,很多打了标签却不内链。也不知道是不是我没有设置对。

最近又在网上找了一个方法,不利用插件来实现TAG内链,当然也是听到网友说使用插件会使网站速度变慢,索性直接换成了代码方式实现。

将代码放在当前主题Functions.php 文件中。

也可通过后台 外观-主题编辑器 进入编辑。

将代码放在结尾 ?> 的前面

//自动TAG转内链
$match_num_from = 2; // 一个TAG标签出现几次才加链接
$match_num_to = 1; // 同一个标签加几次链接
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, '$'),__('View all posts in %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;
}

原创文章,作者:五车二,如若转载,请注明出处:http://www.5che2.com/article/155.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值