Skip to content

Instantly share code, notes, and snippets.

@overclokk
Forked from jawinn/CreateWordpressUser.php
Last active November 21, 2017 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save overclokk/e63c15eb274532b68502685dc2952d26 to your computer and use it in GitHub Desktop.
Save overclokk/e63c15eb274532b68502685dc2952d26 to your computer and use it in GitHub Desktop.
Create WordPress Admin User from PHP
<?php
/**
* ADD NEW ADMIN USER TO WORDPRESS
*
* Put this file in your WordPress root directory and run it from your browser.
* Add wp-new-user.php after your domain url.
* Delete it when you're done.
*
* @link https://gist.github.com/overclokk/e63c15eb274532b68502685dc2952d26
* @since 1.0.0
*
* @requirement WP >= 3.1
*/
require_once( 'wp-blog-header.php' );
/**
* CONFIG VARIABLES
* Make sure that you set these before running the file.
*/
$newusername = ''; // <- Enter the user name.
$newpassword = ''; // <- Enter the user password.
$newemail = ''; // <- Enter the user email.
$role = 'administrator'; // <- Enter the user role. Default 'administrator'
//----------------------------------------------------------//
if ( empty( $newusername ) ) {
echo 'Whoops, looks like you did not set a username<br>';
return;
}
if ( empty( $newpassword ) ) {
echo 'Whoops, looks like you did not set a password<br>';
return;
}
if ( empty( $newemail ) ) {
echo 'Whoops, looks like you did not set an email<br>';
return;
}
if ( false === is_email( $newemail ) ) {
echo 'Whoops, looks like this is not a valid email<br>';
return;
}
if ( ! in_array( $role, array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' ) ) ) {
echo 'Whoops, The user role is not set correctly.<br>';
return;
}
if ( username_exists( $newusername ) ) {
echo 'The user name already exists.<br>';
return;
}
if ( email_exists( $newemail ) ) {
echo 'The user email already exists.<br>';
return;
}
/**
* User ID|WP_Error
*
* @var int|WP_Error
*/
$user_id = wp_create_user( $newusername, $newpassword, $newemail );
if ( is_wp_error( $user_id ) || 0 === $user_id ) {
echo 'Error with wp_insert_user. No users were created.';
} else {
$wp_user_object = new WP_User( absint( $user_id ) );
$wp_user_object->set_role( $role );
echo 'Successfully created new ' . $role . ' user. Now delete this file!';
}
return;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment