I want to create user with some custom fields. I have created extra fields through config > people > site information > manage fields and fields like first name, last name, city etc. I want to create user with this custom fields.

How can I create user programmatically?

up vote 24 down vote accepted

Using user_save Drupal function you can create new users like so:

$new_user = array(
  'name' => 'JohnDoe',
  'mail' => 'john.doe@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
  //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);
  • I'm not sure what access does, I've copied this from the user_save page's comments on d.o and modified them, so I'm not 100% on what access does. I'm gonna assume that it's the last access date, so if it's a new user, I'm guessing it shouldn't be set. – Beebee Apr 11 '13 at 15:10
  • thanks its working good for me. and sorry for late replay. – Pranav Gandhi Apr 12 '13 at 10:02
  • @GandhiPranav Don't forget to accept the answers to your questions if they've helped you out; this lets future visitors know that a particular solution was the one that solved your specific problem, and it rewards the answerer for their efforts. You can accept an answer by clicking the checkmark underneath the vote indicator. Thanks :) – Clive Apr 12 '13 at 11:27
  • Access is just the last access field (like the "created" field – ergophobe Jun 6 '14 at 7:07
  • This works to create new users, but isn't there a "preferred" entity way like with nodes? Something involving entity_create_stub_entity('user') or entity_metadata_wrapper(..)? I ask because I have been struggling doing it the entity way.. :) – texas-bronius Apr 23 '15 at 22:01

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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