- A+
所属分类:WordPress
WordPress文章关键词自动内链到相关标签页,提高网站的SEO,增加用户粘性
前言
大家都知道,我们访问一个网站的时候,经常是漫无目的的浏览的,看到什么就点击什么,点击的越多,用户在你的网站的留存时间也就越长。那么对你的网站就有好处。那么怎么增加用户点击量呢,给文章中的关键词添加标签页面额链接是一个很不错的方法。这里就给大家推荐这个使用代码的WordPress文章自动内链的方法。
函数代码
将以下代码添加到functions.php
文件倒数第二行。
- //WordPress文字标签关键词自动内链
- $match_num_from = 1; //一篇文章中同一個標籤少於幾次不自動鏈接
- $match_num_to = 4; //一篇文章中同一個標籤最多自動鏈接幾次
- 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, '$'),__('查看更多关于 %s 的文章'))."\"";
- $url .= ' target="_blank"';
- $url .= ">".addcslashes($cleankeyword, '$')."</a>";
- $limit = rand($match_num_from,$match_num_to);
- $content = preg_replace( '|(<a[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</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;
- }
- add_filter('the_content','tag_link',1);