How To Programmatically Add a User and Set User Role

How To Programmatically Add a User Set User Role

If you missed it, I was working on a massive data import from another e-commerce system to WooCommerce. I detailed how to programmatically updated billing information for a user. There are a few things I manually programmed to make the import work. This post will go over how I used a spreadsheet of information to add new users and then set them as a customer role type for WooCommerce.

Before doing anything that has to with users, I had to make sure that the users actually existed in the system. I wouldn’t be able to add billing info for users that aren’t in there yet. So, I first had to get them in there and make sure they had the correct permissions.

WordPress already has built-in functions to programmatically add a user and to update user roles. It’s just a matter of knowing what code. This example below creates a user and saves the returned new user id in a variable. It then uses that new user id to change the role.

$user_id = wp_create_user($username, $password, $email); // create the user and save the returned user id

if ( is_numeric( $user_id ) ) { // make sure the user id is a number, it can fail
  $user = new WP_User( $user_id ); // create a new user object for this user
  $user->set_role( 'customer' ); // set them to whatever role you want using the full word
}

Leave a Reply

Your email address will not be published. Required fields are marked *