您无需通过为每个术语添加规则即可实现此目的rewrite
注册帖子类型和分类时的参数。唯一需要的额外规则是处理分类法的分页。
首先,注册post类型。注册帖子类型和分类的顺序很重要!我省略了大多数论点,将重点放在重要的方面:
$args = array(
\'has_archive\' => \'custom-type\',
\'rewrite\' => array(
\'slug\' => \'custom-type/%custom-tax%\',
\'with_front\' => false
)
);
register_post_type( \'custom-type\', $args );
然后注册分类:
$args = array(
\'rewrite\' => array(
\'slug\' => \'custom-type\',
\'with_front\' => false
)
);
register_taxonomy( \'custom-tax\', array( \'custom-type\' ), $args );
然后添加重写规则以处理分类分页:
function wpd_taxonomy_pagination_rewrites(){
add_rewrite_rule(
\'custom-type/([^/]+)/page/([0-9]+)/?$\',
\'index.php?custom-tax=$matches[1]&paged=$matches[2]\',
\'top\'
);
}
add_action( \'init\', \'wpd_taxonomy_pagination_rewrites\' );
要在permalink中获取所选术语,请过滤
post_type_link
:
function wpd_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) && $post->post_type == \'custom-type\' ){
$terms = wp_get_object_terms( $post->ID, \'custom-tax\' );
if( $terms ){
foreach( $terms as $term ){
if( 0 == $term->parent ){
return str_replace( \'%custom-tax%\' , $term->slug , $post_link );
}
}
} else {
return str_replace( \'%custom-tax%\' , \'uncategorized\', $post_link );
}
}
return $post_link;
}
add_filter( \'post_type_link\', \'wpd_post_link\', 1, 3 );