Problem with rules occurs, because rule for a given projecttype
is added when you visit relevant URL.
Every time you visit one of projects/{projectstype}/
addresses and flush rewrite rules,
they are deleted and only one rule (only for current project type) is saved/created.
You can add your code to request
filter hook, then there is no need to add rewrite rules.
All query vars, that are set by rules (you set only page_id
), you can set manually.
add_filter( 'request' , 'se336968_request' );
function se336968_request( $query_vars )
{
if(substr( $_SERVER['REQUEST_URI'], 0, 11 ) === '/projects/'){
$request_subpage = str_replace("https://wordpress.stackexchange.com/", '', str_replace('/projects/', '', $_SERVER['REQUEST_URI']));
if($request_subpage !== '') {
$project_types = get_posts( array( 'post_type' => 'projecttype', 'posts_per_page' => -1 ) );
foreach( $project_types as $project_type ) {
if( $project_type->post_name === $request_subpage ) {
// your current rewrite
$query_vars['page_id'] = 8;
$query_vars['post_type'] = 'page';
// --- to open "projecttype" type post from URL ---
// $query_vars['post_type'] = 'projecttype';
// $query_vars['projecttype'] = $request_subpage;
// unset( $query_vars['page_id'], $query_vars['p'], $query_vars['pagename'], $query_vars['name'] );
break;
}
}
}
}
return $query_vars;
}