Adding custom user roles fields to Drupal 7 user register

Our task is to add custom user roles fields{Radio buttons} using form api to Drupal 7 user register page and save the user with the same role.


Step 1: Add Author and Editor role.{admin/people/permissions/roles}

User roles

Step 2: Create your own custom module

this module is required for implementing required hooks

Step 2: Implements hook_form_alter

Implements hook_form_alter hook in your module_name.module file

 * Implements hook_form_alter
function module_name_form_alter(&$form, &$form_state, $form_id) {
  $user_roles = array(4 => 'Author', 5 => 'Editor');
  switch ($form_id) {
    case 'user_register_form':
      $form['user_roles'] = array(
        '#type' => 'radios',
        '#title' => t('Roles'),
        '#options' => $user_roles,
        '#default_value' => 4,

Open Create new account page{user/register}, the roles radio buttons is added on user register page.

User register page

Step 3: Implements hook_user_insert

Implements hook_user_insert hook in your module_name.module file

 * Implements hook_user_insert
function module_name_user_insert(&$edit, $account, $category){
  $user_roles = array(4 => 'Author', 5 => 'Editor');
  $role = $edit['user_roles'];
  $account->roles[$role] = $user_roles[$role];

assign selected role to the use.

Do not use user_save() function inside the hook_user_insert