1

I'm using WP to work as the CMS for a website which will be provided to users of a number of different products. I've successfully created a function which will redirect users based on their role:

add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
function my_login_redirect( $redirect_to, $request, $user ) {
if ( is_array( $user->roles ) ) {
    if ( in_array( 'administrator', $user->roles ) )
        return home_url( '/wp-admin/' );
    elseif ( in_array( 'editor', $user->roles ) )
        return home_url( '/wp-admin/' );
    elseif ( in_array( 'subscriber', $user->roles ) )
        return home_url();
    elseif ( in_array( 'map_user', $user->roles ) )
        return home_url( '/mapping/' );
    elseif ( in_array( 'news_subscriber', $user->roles ) )
        return home_url( '/category/newsletter/' );
    else
        return home_url();
}

Some users need to be redirected to a specific page which shares their username.

How can I retrieve the username and incorporate it into their redirect? So:

...
elseif ( in_array( 'map_user', $user->roles ) )
    return home_url( '/mapping/[username-based-page-goes-here]/' );
...

[I'm aware of Peter's Redirect plugin, I'd rather make use of Wordpress core functions to save on having to manually tailor each user's access upon creation. I also make use of other plugins which seem to conflict with Peter's.]

1

$user->data should have what you want.

// snip
elseif ( in_array( 'map_user', $user->roles ) )
    return home_url( "/mapping/{$user->data->user_login}/" );
// end snip

Add if (!is_wp_error($user)) wp_die(var_dump($user)); to the top of your function to see what you have to work with. Caution: This will break things. (It throws a notice as well) It is for debugging only.

  • Hi @s_ha_dum - thanks for the suggestion. Trying this resulted in the login being forwarded to '[home]/mapping/user-data-user_login/' rather than the user name itself. Any thoughts? – shngrdnr Feb 13 '13 at 15:40
  • You didn't change the single quotes in your code to double quotes to match my code. :) – s_ha_dum Feb 13 '13 at 15:48
  • Ha! Okay, okay, you got me! Thanks for the assist :) – shngrdnr Feb 13 '13 at 15:52

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.