# Editing the variables in a custom URL

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);
}
}



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');  ## 1 Answer IMHO easiest way to do the trick is use a simple rewrite rule, and demand the logic to the page, e.g. function my_custom_url() { add_rewrite_rule('story/([^/]+)/?','index.php?pagename=story&user=$matches[1]','top');
}

$userqv = get_query_var('user');$user = is_numerical( $userqv ) ?$userqv : get_user_id( $userqv );  In this way the $user variable will be set to whatever is after the url if it's a number, and if something not numerical is used in url, it will treated as an username and the user id is get accordingly.