乌徒帮技术范儿WordPressWordPress开发 › 自主设置post_type_link格式,在post_type固定链接中使用post_id

自主设置post_type_link格式,在post_type固定链接中使用post_id

分类:WordPress开发

在我们之前的文章《register_post_type后的permalink固定链接和register_meta_box_cb问题》中,我们已经提到过新的post_type注册后链接不能访问的处理办法。但post_type文章的固定链接形式其实只能是/post_type/post_name的形式,而不能成为post_type/post_id形式,可是我们常常希望某种特殊文章只用post_id来作为访问地址,例如产品、书籍等。

这个问题再wordpress的讨论版中已经被讨论过,请看这里看看他们都在怎么讨论。经过总结,实现这一方法在这篇文章已经解决。

最后的代码如下:

add_action('init', 'post-type_rewrite');
function post-type_rewrite() {
	global $wp_rewrite;
	$queryarg = 'post_type=post-type&p=';
	$wp_rewrite->add_rewrite_tag('%post_id%', '([^/]+)', $queryarg);
	$wp_rewrite->add_permastruct('post-type', '/post-type/%post_id%', false);
}
 
add_filter('post_type_link', 'post-type_permalink', 1, 3);
function post-type_permalink($post_link, $id = 0, $leavename, $sample) {
	global $wp_rewrite;
	$post = &get_post($id);
	if ( is_wp_error( $post ) )return $post;
	$newlink = $wp_rewrite->get_extra_permastruct('bodumanzaru');
	$newlink = str_replace("%post_id%", $post->ID, $newlink);
	$newlink = home_url(user_trailingslashit($newlink));
	return $newlink;
}

不过可惜的是,这段代码基本可以解决只有一个post_type的情况,而如果规定了几个post_type的话,就会导致每一个post_type的开头都是post-type,但实际我们希望每个post_type都可以自己定义自己的URL。现在有一个问题是,我只希望product采用post_id作为访问路径,那么,我们将后面的函数写成下面这个样子。

add_filter('post_type_link','my_product_permalink');
function my_site_permalink($post_link, $id = 0, $leavename = false, $sample = false) {
	global $wp_rewrite;
	$post = &get_post($id);
	if($post->post_type == 'product'){
		if ( is_wp_error( $post ) )return $post;
		$newlink = $wp_rewrite->get_extra_permastruct('product');
		$newlink = str_replace("%post_id%",$post->ID,$newlink);
		$newlink = home_url(user_trailingslashit($newlink));
		return $newlink;
	}else{
		return $post_link;
	}
}

即在里面添加了一个if($post->post_type == 'product')的判断,而如果需要规定其他post_type的URL规则,则可以再增加if判断字句。总之,这种问题总归是要解决的。

已有2条评论 快速评论
  1. 否子戈 #3709楼 回复给@3707楼 2013/06/14 22:41:09 回复

    本站专注研究WordPress,你可以看看以前的文章,即可了解我的开发路程

  2. 平推票据针式打印机 #3707楼 2013/06/13 16:11:30 回复

    博主果然是技术党哈!

填写个人信息,赶快回复吧!