1

I'm trying to place a simple bunch of codes to redirect the 'Subscribers' only, to the home page (or a desired page) after login. I thought to use if( current_user_can('read') ):, but that's a global capability, will be applicable for all the other roles too. So I tried get_role('subscriber'). Here are my functions.php codes (thanks to Len):

function subscriber_redirection() {
    global $redirect_to;
    if( get_role('subscriber') ) {
        if ( !isset( $_GET['redirect_to'] ) ) {
            $redirect_to = get_option('siteurl');
        }
    }
}

But it's redirecting the administrators too!

  • How can I target only a specific user role for a purpose?
3

get_role is just going to return information about the role. It isn't going to tell you if the current user has that role. Use wp_get_current_user with a check something like this:

function subscriber_redirection() {
    global $redirect_to;
    $user = wp_get_current_user();
    if (in_array('subscriber',$user->roles)) {
        // user has subscriber role
        if ( !isset( $_GET['redirect_to'] ) ) {
            $redirect_to = get_option('siteurl');
        }
    }
}

I don't know why you are using global $redirect_to; but never do anything with the variable.

2

'get_role' returns an object, not a boolean: http://codex.wordpress.org/Function_Reference/get_role

// for example: if the user can not moderate comments
if (!current_user_can('moderate_comments') ) {

//redirect

}

You can find all capabilities here: http://codex.wordpress.org/Roles_and_Capabilities

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.