URL rewrites and pagination

Extending @Stephen Harris’ excellent answer, I would opt for;

add_action( 'generate_rewrite_rules', 'my_rewrite_rules' );
function my_rewrite_rules( $wp_rewrite )
{
    $wp_rewrite->rules = array(
        'mypageslug/([^/]+)/page/?([0-9]{1,})/?$' => $wp_rewrite->index . '?pagename=mypageslug&user=" . $wp_rewrite->preg_index( 1 ) . "&paged=' . $wp_rewrite->preg_index( 2 ),
        'mypageslug/([^/]+)/?$' => $wp_rewrite->index . '?pagename=mypageslug&user=" . $wp_rewrite->preg_index( 1 )

    ) + $wp_rewrite->rules;
}

This follows the defacto regex standard used in WordPress core. The main change from Stephen”s code sample is the use of $wp_rewrite->index to ensure the rewrite is passed through to WordPress (otherwise it may get added to the ‘external’rewrite list).

Secondly, and most importantly, passing the pagename var in the query string – this means WordPress will behave as if it were ordinarily loading a page with the slug mypageslug.

UPDATE: I forgot to add, make sure user is a public query var, otherwise WordPress won’t map it from the URL. Either filter it in with query_vars or add it using the global $wp;

add_filter( 'query_vars', 'my_query_vars' );
function my_query_vars( $vars )
{
    $vars[] = 'user';
}

// my preferred method - make sure you run this only after 'init' has fired!
$GLOBALS['wp']->add_query_var( 'user' );

// then once the request has been parsed (anything after the action 'parse_request')
$user = get_query_var( 'user' );

Leave a Comment