First, you need to register the %office%
rewrite tag:
// First, add the rewrite tag.
add_rewrite_tag( '%office%', '([^/]+)', 'post_type=office_members&office_name=" );
// Then call add_permastruct().
add_permastruct( "office_members', ... );
Then, add the custom office_name
arg to the public query vars so that WordPress reads/parses it from the URL:
add_filter( 'query_vars', function ( $vars ) {
$vars[] = 'office_name';
return $vars;
} );
And use the pre_get_posts
hook to load the correct office_members
posts that are children of the offices
post with the slug in the 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, "https://wordpress.stackexchange.com/" ) ) ? 'offices' : 'name';
$ids = get_posts( "post_type=offices&{$arg}=$slug&fields=ids" );
if ( ! empty( $ids ) ) {
$query->set( 'post_parent', $ids[0] );
}
}
} );
Now the members archive page should show the proper posts, but we need to fix the pagination for that page, and for that reason, we can use the parse_request
hook:
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];
}
} );
And btw, you’ve got a typo in your register_post_type()
args: You used support
, but the correct arg name is supports
(note the second “s”).