欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」WordPress 文章关键词自动内链

作者 : 自学哈 本文共1535个字,预计阅读时间需要4分钟 2022-11-26 共93人阅读
也想出现在这里? 联系我们

今天有个收费用户向我询问了一些关于网站内链的优化,也就提及到了 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 标签关键词链接,有一定的局限性吧!

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

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」WordPress 文章关键词自动内链
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号