0

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');
0

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');
}    
add_action( 'init', 'my_custom_url' );

After that in page where you need the user id use:

$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.

  • Thanks! I was trying to avoid editing the original page's PHP, but I agree this is probably more straight-forward. I'd still be interested to see anyone's solutions to changing the URL without editing the page's code though. – user2950747 Dec 14 '13 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.