Auto-Upgrading users in WordPress

I made a small site recently where I wanted all newly registered users from a specific email domain to automatically be administrators (this is a terrible idea, don’t do it).  The user registration was restricted by Single-Sign-On and 2-Factor Authentication, so I felt relatively safe doing this, especially since it was only a “for fun” project.

The interesting bit of code that upgraded users to admins is as follows:

 

add_action( 'user_register', 'upgrade_email_to_admin', 10, 1 );
function upgrade_email_to_admin( $user_id ) {
	$user = get_user_by( 'ID', $user_id );
	if ( false !== $user ) {
		$email = $user->data->user_email;

		// Only example.com please.
		if ( false === strpos( $email, '@example.com' ) ) {
			return;
		}

		$roles = $user->roles;

		if ( ! in_array( 'administrator', $roles, true ) ) {
			$user_update = array();
			$user_update['ID'] = $user_id;
			$user_update['role'] = 'administrator';
			wp_update_user( $user_update );
		}
	}
}

This is 100% insecure, please do not do this :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s