之前一直使用WP keyword link这个插件给文章中的关键字增加内链,以优化SEO。但插件多了对博客的速度肯定有影响,所以找了个无插件实现的方法。实现起来也很简单,只需在主题文件夹中的function.php最后一个?>之前增加以下代码即可实现tag自动内链:
//tag自动内链 $match_num_from = 1; //一篇文章中同一个关键字少于多少不锚文本(这个直接填1就好了) $match_num_to = 2; //一篇文章中同一个关键字最多出现多少次锚文本(建议不超过2次) //连接到WordPress的模块 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 = "<a title="\"".str_replace('%s',addcslashes($cleankeyword," href="\"$link\"" target="_blank">".addcslashes($cleankeyword, '$')."</a>"; $limit = rand($match_num_from,$match_num_to); //不连接的代码 $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(]*>)|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; }
更新你的博客看看,是不是已经有效果啦?
代码来自互联网,有改动。
鉴于网上发布者太多,无法判断原作者是哪位,就不贴原po地址了,再次谢过提供源码的作者们。
加了上面的代码之后,网站500了………………
请问博主访客留言的网址是转成内链的啊?有什么插件么?
兄弟,你这个提示关闭广告拦截的功能是怎么来的啊?自己写的代码还是插件么?
tag词只出现一个,您注意到了吗
我的博客一直使用wp-keyword-link内链插件,可锚文本颜色还不会改,应该说是技术还不够,今天有幸来到本站学习,希望以上知识能对我有帮助,谢谢了!