Here is a guide on how you can create a user programmatically in WordPress using PHP.
With the following code snippet to be inserted in the functions.php file, you can create a user programmatically. The function is activated when the WordPress functions are initialised, i.e. every time you load a page. If you copy the code snippet to your website, remember to fill in your own user information 🧐.
// Function to create a user programmatically
function create_user_programmatically() {
// Define user credentials
$username = 'new user';
$password = 'lennartc123';
$email = 'lennartc@eksempel.dk';
// Check if the user already exists
if (username_exists($username) || email_exists($email)) {
return;
}
// Create the user
$user_id = wp_create_user($username, $password, $email);
// Assign the user role
$user = new WP_User($user_id);
$user->set_role('subscriber'); // can also be other roles e.g. "administrator"
}
// Run the function when WordPress is initialised
add_action('init', 'create_user_programmatically');
How does the feature work and is it secure?
In this code, we define the user information, such as username, password and email. We then check if the user already exists by using the username_exists() and email_exists() functions. If the user does not exist, we use wp_create_user() to create the user with the provided information. Finally, we assign the user role using the set_role() method on the WP_User object.
Once you have inserted this code into your theme, the function will be executed every time WordPress is initialised. This means that a new user will be created with the specified information every time you visit your WordPress site. Therefore, remember to remove the function if it is no longer in use.
It is important to be aware that programmatically creating users can have security implications. Always make sure to implement appropriate security measures and validation of user credentials to avoid misuse.