«

WordPress文章关键词自动添加内链链接

时间:2021-11-5 13:33     作者:lijiayan     分类: 分享


在主题根目录下的functions.php文件的<?php下添加以下代码
1./*
2.*Wordpress文章关键词自动添加内链链接代码
3.*/
4.//连接数量
5.$match_num_from = 1; //一篇文章中同一个关键字少于多少不锚文本(这个直接填1就好了)
6.$match_num_to = 1; //一篇文章中同一个关键字最多出现多少次锚文本(建议不超过1次)
7.//连接到WordPress的模块
8.add_filter('the_content','tag_link',1);
9.//按长度排序
10.function tag_sort($a, $b){
11.if ( $a->name == $b->name ) return 0;
12.return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
13.}
14.//改变标签关键字
15.function tag_link($content){
16.global $match_num_from,$match_num_to;
17.$posttags = get_the_tags();
18.if ($posttags) {
19.usort($posttags, "tag_sort");
20.foreach($posttags as $tag) {
21.$link = get_tag_link($tag->term_id);
22.$keyword = $tag->name;
23.//连接代码
24.$cleankeyword = stripslashes($keyword);
25.$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('查看所有文章关于 %s'))."\"";
26.$url .= 'target="_blank"';
27.$url .= ">".addcslashes($cleankeyword, '$')."</a>";
28.$limit = rand($match_num_from,$match_num_to);
29.//不连接的代码
30.$content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
31.$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
32.$cleankeyword = preg_quote($cleankeyword,'\'');
33.$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
34.$content = preg_replace($regEx,$url,$content,$limit);
35.$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
36.}
37.}
38.return $content;
39.}


标签: 自动标签 标签内链 标签

推荐阅读:

评论:
鸟叔 2022-05-29 01:14
拿走用了,感谢