Skip to content

Instantly share code, notes, and snippets.

@bhowe
Created April 27, 2021 13: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 bhowe/e64162b5b3da7c47df213931440d43d4 to your computer and use it in GitHub Desktop.
Save bhowe/e64162b5b3da7c47df213931440d43d4 to your computer and use it in GitHub Desktop.
Add a user to a WordPress Site
<?php
// ADD NEW ADMIN USER TO WORDPRESS
// ----------------------------------
// Put this file in your Wordpress root directory and run it from your browser.
// Delete it when you're done.
require_once('wp-blog-header.php');
require_once('wp-includes/registration.php');
// ----------------------------------------------------
// CONFIG VARIABLES
// Make sure that you set these before running the file.
$newusername = 'YOURUSERNAME';
$newpassword = randomPassword();
$newemail = 'YOUREMAIL@TEST.com';
// ----------------------------------------------------
// This is just a security precaution, to make sure the above "Config Variables"
// have been changed from their default values.
if ( $newpassword != 'YOURPASSWORD' &&
$newemail != 'YOUREMAIL@TEST.com' &&
$newusername !='YOURUSERNAME' )
{
// Check that user doesn't already exist
if ( !username_exists($newusername) && !email_exists($newemail) )
{
// Create user and set role to administrator
$user_id = wp_create_user( $newusername, $newpassword, $newemail);
if ( is_int($user_id) )
{
$wp_user_object = new WP_User($user_id);
$wp_user_object->set_role('administrator');
echo 'Successfully created new admin user. Now delete this file!';
echo "Password: " . $newpassword;
}
else {
echo 'Error with wp_insert_user. No users were created.';
}
}
else {
echo 'This user or email already exists. Nothing was done.';
}
}
else {
echo 'Whoops, looks like you did not set a password, username, or email';
echo 'before running the script. Set these variables and try again.';
}
function randomPassword() {
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment