Create a WordPress administrator account in code.

If you can't login into you WordPress instance, but you do have filesystem access you can create an admin account in code and get your access back.

Introduction

For whatever reason, sometimes you may need to bypass the WordPress admin GUI and create an adminstrator account in code.

So how do you do that?

It’s easy! Create the following PHP function in your child theme functions.php file.

function wpb_admin_account() {
	$user = 'username';
	$pass = 'password';
	$email = 'name@domain';
	if (! username_exists ( $user ) && ! email_exists ( $email )) {
		$user_id = wp_create_user ( $user, $pass, $email );
		$user = new WP_User ( $user_id );
		$user->set_role ( 'administrator' );
	}
}
add_action ( 'init', 'wpb_admin_account' );

If you then hit your website the account will be automatically created.

Of course, once the account has been created you can safely remove the code from your child theme functions.php file.