You can create a new user programmatically in WordPress using the wp_insert_user() function. Here is an example of how to do this:
<?php
$userdata = array(
'user_login' => 'exampleuser',
'user_url' => 'http://example.com',
'user_pass' => null, // When creating a user, `user_pass` is expected.
'user_email' => 'user@example.com',
'display_name'=> 'Example User',
'nickname' => 'exampleuser',
'first_name' => 'Example',
'last_name' => 'User',
'role' => 'subscriber'
);
$user_id = wp_insert_user( $userdata ) ;
//On success
if ( ! is_wp_error( $user_id ) ) {
echo "User created : ". $user_id;
}
?>Please make sure to replace the dummy data with your actual data. Here is what each key in the $userdata array does:
user_login(string) – The user’s login username.user_pass(string) – The user’s password.user_nicename(string) – A URL-friendly version of the user’s username.user_email(string) – The user’s email.user_url(string) – The user’s URL.display_name(string) – The user’s display name.nickname(string) – The user’s nickname.first_name(string) – The user’s first name.last_name(string) – The user’s last name.description(string) – The user’s bio.role(string) – The user’s role.
In the role section, you can specify the user role such as ‘administrator’, ‘editor’, ‘author’, ‘contributor’ or ‘subscriber’.
Remember, you will need appropriate permissions to create a user in WordPress.
Finally, wp_insert_user() returns the new user’s ID if the user is successfully created, or a WP_Error object if the user could not be created. Therefore, it’s important to check whether the return value is a WP_Error object before proceeding.
Leave a Reply