WordPress无插件自动实现tag关键字内链,抛弃wp-keyword-link

多添加内部链接对网页排名是有很大好处的

插件wp-keyword-link可以实现自动内链

由于插件使用太多造成服务器负担,所以会改wordpress的还是使用代码吧

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

将上面的代码添加到wordpress主题中的functions.php这个文件中,保存就ok了,效果跟我这里的一样,

添加之前记得备份.

标签