免插件用Tags做文章关键字内链
在我第二次优化博客的过程中《博客优化续》,提到过免插件使用tags作为文章关键字站内链接。
通过这种方法我们可以将文章里面的所有tag添加上链接,链接链到博客的tag标签页面,这样做不但方便我们查看相关文章,而且也有利于博客的seo优化(据说)。
几个月过去了,感觉这个内链还是蛮实用的,于是将代码分享给大家。其实这类代码网上挺多的,大家可以根据自己的需求选择修改。
方法如下:打开wordpress主题的function.php文件,在这个文件里面添加如下代码:
[task]
//连接数量
$match_num_from = 1; //一个关键字少于多少不替换
$match_num_to = 10; //一个关键字最多替换
//连接到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 href=\”$link\” title=\””.str_replace(‘%s’,addcslashes($cleankeyword, ‘$’),__(‘View all posts in %s’)).”\””;
$url .= ‘ target=”_blank”‘;
$url .= “>”.addcslashes($cleankeyword, ‘$’).”</a>”;
$limit = rand($match_num_from,$match_num_to);
//不连接的 代码
$content = preg_replace( ‘|(<a[^>]+>)(.*)(‘.$ex_word.’)(.*)(</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;
}
[/task]
就这么简单,心动不如行动~~
xiaofeng
2013年3月3日 19:13
么有博客啊
wonse
2013年3月3日 20:21
@xiaofeng 😆 呵呵
简搜百科
2013年3月4日 09:38
晕了。。。
Win8迷
2013年3月4日 11:59
代码版不错! 用插件版比较好控制 😯 各有所需吧
wonse
2013年3月4日 12:45
@Win8迷 呵呵,不想添加插件了
苦逼男
2013年3月4日 13:35
不错,值得参考。
wonse
2013年3月5日 23:56
@苦逼男 感觉还是蛮有用的 😆
weipu2010
2013年3月4日 13:53
这分明是技术贴
wonse
2013年3月5日 23:57
@weipu2010 wordpress用到的,和你无关。。。
小刀
2013年3月4日 17:52
好久没来了 😎
wonse
2013年3月5日 23:57
@小刀 欢迎来玩 🙂
亲门128
2013年3月4日 20:37
不错呢,好
bbis
2013年3月5日 15:06
有了插件版默认设置
南寻
2013年3月7日 10:12
自己手动插入的说… 😮
石博文.IT博客
2013年3月8日 23:26
好漂亮的博客
Ashe
2013年3月10日 13:01
不错,抱走
囧小样
2013年3月12日 11:10
管用不?等下试试