Rather than touch $wp_rewrite directly, I would use WordPress’s helper functions:
/**
* Setup the new rewrite tags, rules, and permalink structure
*/
function foo() {
// Setup some variables
$rewrite_tag = 'some_unique_id';
$root_slug = 'role-name';
// Add the custom query variable
add_rewrite_tag( '%' . $rewrite_tag . '%', '([^/]+)' );
// Add the custom rewrite rule
add_rewrite_rule( $root_slug . '/([^/]+)/?$', 'index.php?' . $rewrite_tag . '=$matches[1]', 'top' );
// Add the custom permalink structure
add_permastruct( $rewrite_tag, $root_slug . '/%' . $rewrite_tag . '%', array(
'with_front' => false,
'ep_mask' => EP_NONE,
'paged' => true, // maybe false for you?
'feed' => false, // maybe true for you?
'forcomments' => false,
'walk_dirs' => true,
'endpoints' => false
) );
}
add_action( 'init', 'foo' );
/**
* Parse the query for your specific rules
*/
function bar( $posts_query ) {
// Bail if $posts_query is not the main loop
if ( ! $posts_query->is_main_query() )
return;
// Bail if filters are suppressed on this query
if ( true === $posts_query->get( 'suppress_filters' ) )
return;
// Bail if in admin
if ( is_admin() )
return;
// Look for the user query variable match
$our_user = $posts_query->get( 'some_unique_id' );
// User match?
if ( !empty( $our_user ) ) }
// Do your thing
var_dump( $our_user );
// Set a variable to use later
$posts_query->our_user = $our_user;
}
}
add_action( 'parse_query', 'bar' );
/**
* Filter template_include, and maybe pull in a custom user role template.
*/
function foo_template_include( $template = '' ) {
global $wp_query;
if ( !empty( $wp_query->our_user ) ) {
$template = get_query_template( 'some-file' );
}
return $template;
}
add_filter( 'template_include', 'foo_template_include' );
The above snippet isn’t tested, but it’s similar to what bbPress does, and what WordPress core already does. In the “Do your thing” section, you may want to setup other query variables if you have other decisions you need to make.