Information exchange is vital for making the world a better place.
The Internet must grow and I'm here to help.

WordPress hooks: user_register

Meta data: posted by Rares on 21 April 2011. Categories: Articles, Hooks, WordPress. 9 comments.

I’m gonna keep things short in this article and show you how you can automatically alter WordPress user data after registration.

Use Case: Changing the user’s Display Name

One of WordPress’ present shortcomings is the lack of a configuration option to specify a default display name format for your users. The last sentence was long, so let me give you an example.

Let’s say you’ve allowed user registration on your WordPress website (Settings – General) but instead of the plain username, you want to display their full name on the articles they submit.

You have two options. Either you independently edit each user and change the ‘Display Name’ option or…

Enter the ‘user_register’ hook

This action hook runs immediately after the successful registration of a new user on your website. It passes on the user ID to the callback function. For our purpose, the code is very simple:

class myUsers {
	static function init() {
		// Change the user's display name after insertion
		add_action( 'user_register', array( __CLASS__, 'change_display_name' ) );
	}

	static function change_display_name( $user_id ) {
		$info = get_userdata( $user_id );

		$args = array(
			'ID' => $user_id,
			'display_name' => $info->first_name . ' ' . $info->last_name
		);

		wp_update_user( $args );
	}
}

myUsers::init();

First, we grab the newly created user information with the get_userdata() function. Then, we concatenate the first name and the last name and feed it as an argument to wp_update_user().

Just paste this into your functions.php file and you’re all set.

References

Thank you for [retweet-anywhere].