Update user’s first_name, last_name and email on a WordPress website when the appropriate MailChimp data has been changed

If you are interested in an opposite process – how to sync MailChimp lists with changes on your website, I recommend to look at my plugin.

Creating a webhook

First of all go to your MailChimp dashboard to create a webhook that will be fired when somebody has updated his profile or changed his email (check checkboxes Profile updates and Email changed).

Creating a webhook that processes two events at the same time – profile update and email changed.
What sources to set depends directly on your purpose, but in the common cases it is enough to set “By a subscriber”.

As you can see, we have a single webhook for both events. If this step seems unclear for you, or maybe you would like to create a webhook with MailChimp API, I recommend to check this tutorial first.

Update a user on your WordPress website

Even if you are not so familiar with the code, no problems – all you have to do is to insert this ready-to-use piece of code to your (child) theme functions.php. Just in case you changed the webhook URL above, do it here as well.


add_action( 'init', 'misha_profile_and_email_update_webhook');
 
function misha_profile_and_email_update_webhook(){

	// exit the function in case it is not our hook
	if( empty( $_GET['process-webhook'] ) || empty( $_POST['type'] ) || $_GET['process-webhook'] != 'anything' )
		return;

	$event_type = $_POST['type'];
	
	switch( $event_type ) :
		case 'profile':
		
			// we need it because we have to get a User ID somehow
			$user = get_user_by( 'email', $_POST['data']['email'] );

			wp_update_user( array( 
				'ID' => $user->ID, 
				'first_name' => $_POST['data']['merges']['FNAME'],
				'last_name' => $_POST['data']['merges']['LNAME'],
				'display_name' => $_POST['data']['merges']['FNAME'] . ' ' . $_POST['data']['merges']['LNAME'] 
			) );

			// you can also use update_post_meta() by the wa
			//update_user_meta( $user->ID, 'first_name', $_POST['data']['merges']['FNAME'] );
			
		die;
		case 'upemail':

			$user = get_user_by( 'email', $_POST['data']['old_email'] );

			wp_update_user( array( 
				'ID' => $user->ID, 
				'user_email' => $_POST['data']['new_email']
			) );
		
		die;
	endswitch;

}

I replaced break with die on lines 27 and 37 because we do not have to do anything else (load a website page 😱) once the appropriated to a certain webhook code is fired.

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on Twitter