wordpress 标签页tag改成id格式的代码

技术控 Loading... 阅读

代码如下:

// WordPress 文章标签以id方式展示
add_action('generate_rewrite_rules','tag_rewrite_rules');
add_filter('term_link','tag_term_link',10,3);
add_action('query_vars', 'tag_query_vars');
function tag_rewrite_rules($wp_rewrite){
	$new_rules = array(
// 		'tag/(\d+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?tag_id=$matches[1]&feed=$matches[2]',
// 		'tag/(\d+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?tag_id=$matches[1]&feed=$matches[2]',
		'tag/(\d+)/embed/?$' => 'index.php?tag_id=$matches[1]&embed=true',
		'tag/(\d+)/page/(\d+)/?$' => 'index.php?tag_id=$matches[1]&paged=$matches[2]',
		'tag/(\d+)/?$' => 'index.php?tag_id=$matches[1]',
	);
	$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

function tag_term_link($link,$term,$taxonomy){
	if($taxonomy=='post_tag'){
		return home_url('/tag/'.$term->term_id.'/');  
	}
	return $link;
}

function tag_query_vars($public_query_vars){  
	$public_query_vars[] = 'tag_id';  
	return $public_query_vars;  
}

简单的说就是把之前默认的 https://boke.slhq.cn/tag/我的网站 改成 https://boke.slhq.cn/tag/888/ 这种格式,这种格式的好处就是方便管理,比如生成静态页或者提交到搜索引擎能一眼看清楚,默认的中文路径需要经过转码之类的,我的后台有不少404链接,都是tag转码的问题,所以我直接用id格式就避免了这一类的问题。

使用方法:把上面的代码放在你wordpress 的functions.php 文件最底下,之后回到后台设置中,选择路径,保存一下就生效了。需要注意,如果已经有了缓存,一定要清除一下缓存。

这个方法只是重写了tag 的url而已,所以,之前默认的访问方式还是有效的,这样就不会导致大批量的404了。

Tags:

版权声明:若无特殊注明,本文皆为《书蓝画青》原创,转载务必保留文章来源。

本文链接:wordpress 标签页tag改成id格式的代码 & https://boke.slhq.cn/1904.html

推荐阅读
分享