How to target specific user role?

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?

Related posts

2 comments

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

Comments are closed.