Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Never build auth again! Okta makes it simple to implement authentication, authorization, MFA and more in minutes. Try the free developer API today! 

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.

<?php 
define('WP_USE_THEMES', false);
require("./blog/wp-load.php");
$user = array('user_login' => 'realin','user_pass' => 'testpass','user_email' => 'user@email.com','role' => 'administrator');
var_dump(wp_insert_user($user));
?>

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/

 

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}