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
33
34
35
36
37
38
/**
 * WordPress 自动为文章标签添加该标签的链接
 * http://www.wpdaxue.com/auto-add-tag-link.html
 */
$match_num_from = 1;  // 一个标签在文章中出现少于多少次不添加链接
$match_num_to = 1; // 一篇文章中同一个标签添加几次链接
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;
}

你可以根据自己的需要修改文章标签的链接数。

PS:真的找不到该代码的原始出处,如果有知道的,烦请告知。

测试:该代码会自动为这篇文章的标签添加链接,但是 $match_num_from 和 $match_num_to 这两个参数的设置很有意思(不够准确,具体请自己测试)

未经允许不得转载:Bcoder资源网 » WordPress 自动为文章标签(关键词)添加该标签的链接

相关推荐

更多优质资源关注微信公众号: bcoder

bcoder
赞 (2)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册
  1. kkoopp如何不区分文章中的大小写来链接呢?标签是小写的字母,文章内是大写的,就链接不了