WordPress自动为文章中的关键词添加链接(不用插件)

说到wordpress自动给标签(关键词)加链接,很多读者估计跟我一样,使用插件呗!毕竟wordpress插件太丰富了,而且都不用费心思,不过装了太多插件的wordpress将会异常臃肿,虚拟主机现在确实不值钱,但是速度越来越慢却是不可忍受的。今天,就来分享个不用插件的方法,也非常的简单,只需简单修改文件即可。

打开主题的functions.php文件(灵活运用,比如本站所用的dux主题的文件就是functions-theme.php),在末尾添加如下代码:

/* 自动为文章内的标签添加内链开始 */ $match_num_from = 1; //一篇文章中同一个标签少于几次不自动链接 $match_num_to = 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 = "" .addcslashes($cleankeyword,="">"; $limit = rand($match_num_from,$match_num_to); $content = preg_replace( '|(]+>)(.*)('.$ex_word.')(.*)(]*>)|U'.$case, '$1$2$4$5', $content); $content = preg_replace( '|()|U'.$case, '$1$2$4$5', $content); $cleankeyword = preg_quote($cleankeyword,'\''); $regEx = '\'(?!((]*?)>)|([^>]*?))\'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); /* 自动为文章内的标签添加内链结束 */

添加代码后,再看看我们添加过关键词标签的文章,是不是已经自动添加了链接?添加关键词链接的个数可以修改第一、二行代码的数值,为了防止SEO优化过度,建议最多添加2个重复的关键词锚文本。不过,这个代码不能自动识别大小写,标签中单词如果大小写跟文章不一致就不会加链接,这时候我们可以加上一行将文章大小写强制改成标签大小写的代码:

//将大小写强行更改为标签的大小写 $content = str_ireplace(urldecode($tag->slug), $tag->name, $content);

欢迎在站内搜索:韩国独立服务器、香港服务器租用99idc、免费代理服务器、动态vps秒换ip、独立ip主机、海外虚拟主机空间、多ip站群服务器、动态vps秒换ip、香港空间、in域名、