我有两个定制的帖子类型
办公室
register_post_type('offices',
[
'labels' => [
'name' => __( 'Offices' ),
'singular_name' => __( 'Office' )
],
'description' => 'Our Office.',
'public' => true,
'hierarchical' => true,
'has_archive' => false,
'menu_icon' => 'dashicons-building',
'support' => ['title', 'custom_fields', 'page-attributes']
]
);Office成员
//Team Members
register_post_type( 'office_members',
[
'labels' => [
'name' => __( 'Team Members' ),
'singular_name' => __( 'Team Member' )
],
'description' => 'Team members for offices.',
'public' => true,
'hierarchical' => false,
'has_archive' => 'offices/([^/]+)/members',
'show_in_menu' => 'edit.php?post_type=offices',
'support' => ['title', 'custom_fields', 'page-attributes']
]
);我希望下面的urls能够工作
example.com/offices -显示了office归档页面
example.com/offices/([^/]+) -显示单个办公页面
example.com/offices/([^/]+)/members -显示成员存档页面,其中父级是办公室
example.com/offices/([^/]+)/members/([^/]+) -显示单个成员页
对于办公室成员,我有以下重写规则
add_permastruct('office_members', '/offices/%office%/members/%office_members%', false, ['walk_dirs' => false]);
add_rewrite_tag('%office_members%', '([^/]+)', 'office_members=');
add_rewrite_rule('^offices/([^/]+)/members/([^/]+)?','index.php?office_members=$matches[2]','top');除了成员存档页面外,我所有的urls都可以工作。它加载模板文件archive-office_members.php,这很好,但是它没有检测到url中的父办公室。因此,它不是只显示该办公室的成员,而是只向所有成员显示。
我如何设置我的url,使它显示成员存档页面,但只显示基于url中的office的成员,所以我的所有4个url都能工作?
发布于 2020-06-26 15:23:54
首先,您需要注册%office%重写标记:
// First, add the rewrite tag.
add_rewrite_tag( '%office%', '([^/]+)', 'post_type=office_members&office_name=' );
// Then call add_permastruct().
add_permastruct( 'office_members', ... );然后,将自定义的office_name arg添加到公共查询vars中,以便WordPress从URL读取/解析它:
add_filter( 'query_vars', function ( $vars ) {
$vars[] = 'office_name';
return $vars;
} );并使用pre_get_posts钩子加载正确的office_members帖子,这是offices post的子条目,其中包含了office_name arg中的段塞:
add_action( 'pre_get_posts', function ( $query ) {
if ( $query->is_main_query() &&
is_post_type_archive( 'office_members' ) &&
$slug = $query->get( 'office_name' )
) {
$arg = ( false !== strpos( $slug, '/' ) ) ? 'offices' : 'name';
$ids = get_posts( "post_type=offices&{$arg}=$slug&fields=ids" );
if ( ! empty( $ids ) ) {
$query->set( 'post_parent', $ids[0] );
}
}
} );现在,成员存档页面应该显示正确的帖子,但是我们需要修复该页面的分页,因此,我们可以使用parse_request钩子:
add_action( 'parse_request', function ( $wp ) {
if ( isset( $wp->query_vars['paged'] ) &&
preg_match( '#^offices/([^/]+)/members/page/(\d+)#', $wp->request, $matches )
) {
$wp->query_vars['paged'] = $matches[2];
$wp->query_vars['office_name'] = $matches[1];
}
} );顺便说一下,您的register_post_type() args中有一个错误:您使用了support,但是正确的arg名称是supports (请注意第二个"s")。
https://wordpress.stackexchange.com/questions/369784
复制相似问题