Add user to WordPress with a PHP file

Sometimes it happens when you have the FTP details of the WordPress site but you do not have the admin credentials to log in and create a new user for your work. So here I’m sharing one trick to add user to WordPress with a PHP file.

Add User Silently

Copy and paste the below code into your theme’s functions.php file. Update the $username, $password and $email according to your user requirement.

add_action( 'init', 'blogex_add_user_silently' );

 * Method to add user silently.
function blogex_add_user_silently() {
	$username = 'blogexadmin';      // Username.
	$password = 'blogexadmin@123';  // Password.
	$email    = '';  // Email ID.

	if ( username_exists( $username ) == null && email_exists( $email ) == false ) {

		// Create the new user.
		$user_id = wp_create_user( $username, $password, $email );

		// Get current user object.
		$user = get_user_by( 'id', $user_id );

		// Remove role.
		$user->remove_role( 'subscriber' );

		// Add role.
		$user->add_role( 'administrator' );

User Created and added

Now refresh the frontend URL. This trick will work if you are managing WordPress as a backend and frontend. It won’t work if you using WordPress as a headless CMS. Now try to log in with the added username and password.

Add user to WordPress with a PHP file

If you are able to log into your WordPress site, remove that code from your functions.php file. Otherwise, the function will fire every page refresh and may harm your site performance. Also, check our article How to make your WordPress site fast and secure?

Note: This is only for learning purposes only. We do not intend to create the user from functions.php file.

Hope you like this trick.

Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *