Over a million developers have joined DZone.

How to: Create a new WordPress user using a PHP function

DZone's Guide to

How to: Create a new WordPress user using a PHP function

· Web Dev Zone ·
Free Resource

Learn how Crafter’s Git-based content management system is reinventing modern digital experiences.

It’s pretty easy to manage users in WordPress when you are logged into WordPress Dashboard as an Administrator. But what if you want to create a user via a PHP function? The method which we are going to discuss is useful when you are creating a plugin or if you want to create a user by simply executing a PHP file.

Other day when I was given FTP access for a WordPress blog and client forgot to give WordPress Admin access, I used the following block of code to create a user with Administrator role using a simple PHP file. Let us see how it works.
To quickly get going, simply copy paste the following code in a file say, user.php, and upload it using FTP in the same directory where wordpress is installed. Open the file in the domain and a new user “realin” will be created with the password, testpass . You can change details in the code as required.

define('WP_USE_THEMES', false);
$user = array('user_login' => 'realin','user_pass' => 'testpass','user_email' => 'user@email.com','role' => 'administrator');

In the above code snippet we are including the wp-load.php to make sure we can use all the WordPress in-built functions. To quickly insert a user we are using the function wp_insert_user. We specify username, password, role and email. If the user is successfully created then it’s user id (integer) is retuned, else an object containing the error message.

You can use the same function to update an existing user’s information. All you need to do is pass the user id in the along with other options. The new options will replace the existing ones. Hope this is going to help you!

Stay Digified!!
Sachin Khosla


Source: http://www.digimantra.com/tutorials/wordpress/create-wordpress-user-php-function/


Crafter CMS is a modern Git-based platform for building innovative websites and content-rich digital experiences. Download this white paper now.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}