0

I'm playing around with the check_user_role function put together by AppThemes; as mentioned in the WordPress current_user_can codex page. In the AppThemes tutorial code it references the following:

// example use for the current user
if ( appthemes_check_user_role( 'customer' )
    _e( "You've got access dude!", 'appthemes' );
else
    _e( "Sorry man, no luck.", 'appthemes' );

I'm wanting to get this to work with more than 1 user role (i.e. 'customrole', 'subscriber') but not having much luck without creating what feels like repetitive code.

The only way I got it to work was to do something like:

if (appthemes_check_user_role( 'customrole' ) || appthemes_check_user_role( 'author' ) ) {
    _e( "You've got access dude!", 'appthemes' );
} else {
    _e( "Sorry man, no luck.", 'appthemes' );
}

Or this:

if (appthemes_check_user_role( 'customrole' ) ) {
    _e( "You've got access dude!", 'appthemes' );
} if (appthemes_check_user_role( 'author' )) {
    _e( "You've got access dude!", 'appthemes' );
}else{
    _e( "Sorry man, no luck.", 'appthemes' );
}

I was wondering if anyone had any suggestions to simplify the code for use with multiple roles?

  • Maybe creating your own function looping through an array of roles you send to that function? if (my_cool_function(array('customrole','author'))) – Richard B May 16 '13 at 7:57
1
if ( wpse_99666_check_user_roles( array( 'customrole', 'author' ) ) )
    _e( "You've got access dude!", 'appthemes' );
else
    _e( 'Sorry man, no luck.', 'appthemes' );


/**
 * Checks if a particular user has one or more roles.
 *
 * Returns true on first matching role. Returns false if no roles match.
 *
 * @uses get_userdata()
 * @uses wp_get_current_user()
 *
 * @param array|string $roles Role name (or array of names).
 * @param int $user_id (Optional) The ID of a user. Defaults to the current user.
 * @return bool
 */
function wpse_99666_check_user_roles( $roles, $user_id = null ) {

    if ( is_numeric( $user_id ) )
        $user = get_userdata( $user_id );
    else
        $user = wp_get_current_user();

    if ( empty( $user ) )
        return false;

    $user_roles = (array) $user->roles;

    foreach ( (array) $roles as $role ) {
        if ( in_array( $role, $user_roles ) )
            return true;
    }

    return false;
}

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.