I have an existing page in a custom theme that expects a URL in this form: /story?user=1
but I'd like to be able to use better URLs as well, eg: /story/username
.
I've tried to add a rewrite rule in functions.php as below, which gets me half-way, allowing URLs like /story/1
:
function my_custom_url() {
add_rewrite_rule('story/([^/]+)/?','index.php?pagename=story&user=$matches[1]','top');
}
add_action( 'init', 'my_custom_url' );
However I'd still like to use the username in the URL. To allow that, I was expecting to change the rewrite rule to this:
add_rewrite_rule('story/([^/]+)/?','index.php?pagename=story&user='.get_user_id($matches[1]),'top');
Where get_user_id()
is a function that returns the id for a specified username, but that doesn't seem to work (as tested with the Rewrite Analyzer plugin).
This answer pointed me towards the parse_query
hook, so I tried something like this (together with the original rewrite rule):
function my_query_var() {
if ($user = get_query_var('user')) {
$id = get_user_id($user);
global $wp_query;
$wp_query->set('user',$id);
}
}
add_action('parse_query','my_query_var');
However that doesn't seem to work either; Rewrite Analyzer shows that the 'user' portion of the URL remains set to whatever was typed after 'story' in the address bar, rather than the result of get_user_id()
.
Any ideas what I should be doing instead? Thanks!
Edit
Probably worth mentioning that I'm registering the user
variable as the below:
function register_query_var($query_vars) {
$query_vars[] = 'user';
return $query_vars;
}
add_filter('query_vars','register_query_var');