Add user settings to specific roles

Is it possible to do this? I already know about get current_user_can(), which does not work like I need. I’d like to be able to use an array if there are multiple roles.

// Check roles to only add fields to necessary users
function check_role( $user ) {
    $user_role = get_user_role($user->ID);

    if($user_role == 'author') {
        return true;
    } else {
        return false;
    }
}
add_action('show_user_profile', 'check_role');
add_action('edit_user_profile', 'check_role');

if(check_role()) {
    add_action('show_user_profile', 'add_user_fields');
    add_action('edit_user_profile', 'add_user_fields');
    add_action( 'personal_options_update', 'save_user_fields' );
    add_action( 'edit_user_profile_update', 'save_user_fields' );
}

Related posts

Leave a Reply

1 comment

  1. On the profile page exists a global variable $profileuser. The member $profileuser->roles is an array of all roles for that user.

    <?php # -*- coding: utf-8 -*-
    // Plugin Name: personal_options
    
    add_action( 'personal_options', 'print_user_roles');
    
    function print_user_roles()
    {
        global $profileuser;
    
        print '<pre>$profileuser->roles = '
            . htmlspecialchars(
                var_export( $profileuser->roles, TRUE ), ENT_QUOTES, 'utf-8', FALSE
            )
            . '</pre>';
    }
    

    Output:

    $profileuser->roles = array (
      0 => 'administrator',
      1 => 'editor',
    )
    

    Use this list to compare the roles.