WordPress 文章关键词自动内链

张子凡 WordPress优化 2015-07-19 09:15:24 阅读(...) 评论(8)

今天有个收费用户向我询问了一些关于网站内链的优化,也就提及到了 WordPress 的实现方法,所以这里就收集整理了一下,其实有一款很著名的 Auto Tags Link 插件貌似就可以解决这个问题,但是 WordPress 不适合过多的使用插件,所以这里才提供了一个代码版的,大家将以下代码添加到当前主题的 functions.php 文件中就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//WordPress 文章关键词自动内链
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){
	$match_num_from = 1;	//一个标签少于几次不链接
	$match_num_to = 1;	//一个标签最多链接几次
	$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);

以上代码只支持 tag 标签关键词链接,有一定的局限性吧!

从子凡对优化的角度来讲,我并不是非常推从这样的方法,感觉这样的用处并不是很大,反而我觉得在手动添加内链更为给力,所以子凡也并没有在泪雪博客上使用该方法,这里把代码贴出来只是给需要的人的一个选择罢了!

更多关于WordPress优化及疑问可以添加QQ群:255308000

除非注明,否则均为泪雪博客原创文章,禁止任何形式转载

本文链接:https://zhangzifan.com/auto-add-tags-links.html

留言评论

登录 后留言