WordPress主题标签自动内链代码如何实现?

WordPress主题是当下做博客网站的之一,主要是后台操作简单,安全性很可以,毕竟是属于的开源系统,相信有不少的伙伴在操作WordPress后台时,你会发现有很多地主题不支持标签自动内链形式,为什么需要这种形式呢?个人觉得他可以起到的效果,于是就有很多地伙伴就去网上找一下相关的WordPress插件来实现,这里小编是不建议大家去使用插件,能不用插件的尽量不要使用插件,使用过多的插件会影响网站的打开速度,从而避免中百度的,其实我可以通过代码去实现这个效果,下面来一起看看吧!

打开当前使用的wordpress主题的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 = ““;
$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 . ‘)(?!(([^<>]*?)>)|([^>]*?))\’s’ . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( ‘%&&&&&%’, stripslashes($ex_word), $content);
}
}
return $content;
}

(0)
上一篇 2022年7月7日
下一篇 2022年7月7日

相关推荐