Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?
share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer
add comment

'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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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