为了网站的SEO,在搭建好wordpess网站后基本上都要设置一下固定链接,而最常用的固定链接是用文章的ID,之前文章我们具体介绍了固定链接的设置方法,

然而,固定链接虽然说是设置好了,但也只是对文章起作用,对文章标签是没有效果的,WordPress文章标签tag的固定链接默认使用标签的别名,如果你的标签是中文,会被urlencode转义成类一大串字符,不信的话你去看看你自己的网站。这样不仅很丑不美观,而且还不利于SEO优化 。

那么如何改善呢,如何把标签tag的固定链接改成id.html呢,那么方法就来了,就是在functions.php里面加入下面的代码就好了。

// 设置文章标签的固定链接
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).html' => 'index.php?tag_id=$matches[1]&feed=$matches[2]',
		'tag/(\d+)/(feed|rdf|rss|rss2|atom).html' => 'index.php?tag_id=$matches[1]&feed=$matches[2]',
		'tag/(\d+)/embed.html' => 'index.php?tag_id=$matches[1]&embed=true',
		'tag/(\d+)/page/(\d+).html' => 'index.php?tag_id=$matches[1]&paged=$matches[2]',
		'tag/(\d+).html' => '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.'.html');  
	}
	return $link;
}

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

具体效果,可以点击文章下面的标签链接试试。和设置网站的固定链接一样,保存了代码后,一定要在后台的“设置——固定链接”里面重新保存一下,要不然会出现404错误。

0

评论0

请先
不经常更新,所以很少进后台,有啥问题,直接网站底部给我发邮件就行。
显示验证码
没有账号?注册  忘记密码?