无插件实现WordPress内页关键词自动Tags内链

admin
admin
admin
376
文章
102
评论
2020年7月10日15:12:46
评论
290

无插件实现WordPress内页关键词自动Tags内链前面买了个网站,转过来以后莫名其妙的tags自动内链掉掉了,于是乎百度了一下,我一般习惯插件解决问题,改代码改的多了后面升级什么的一堆问题, 不过有的朋友也会说插件增加网站负载,降低网站访问速度,其实加个把两个插件能把你的网速拉到多低的程度呢?下面是无插件实现wordpress自动设置便签tags自动内链的代码。

使用环境:linux服务器,WordPress 5.4.2版本,更改当前主题下面的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;
}

大家注意修改之前先原文件进行备份,编辑的时候一定要用专用的代码编辑器编辑,以免出现错误。

这里推荐大家用notepad++编辑器,简洁好用。Notepad

admin
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: