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@localhost/php/wp/blogex';  // 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.

Users

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:

Related Post

How to contribute to a WordPress core in 2024?

How to contribute to a WordPress core in 2024?

How to write optimized WP_Query in WordPress[2 example]?

How to write optimized WP_Query in WordPress[2 example]?

Create a custom REST endpoint in WordPress[1 example]

Create a custom REST endpoint in WordPress[1 example]

How to create a custom shortcode in WordPress

How to create a custom shortcode in WordPress