Sync WordPress User Profile Updates to Mailchimp

In this tutorial we are going to update user’s first and last names in WordPress profile and sync the changes with Mailchimp audience fields. You can also check the basic guide how to work with Mailchimp API in WordPress.

I can also recommend you my Simple Mailchimp Sync plugin that allows to sync users between WordPress and Mailchimp automatically.

In this tutorial we assume that a specific email is already subscribed to your Mailchimp audience, in case you need to sync user registrations as well, then please check this example.

We are going to use profile_update hook which is fired every time a user profile gets updated. Inside the hook we will perform a Mailchimp API request.

add_action( 'profile_update', function( $user_id, $old_userdata, $userdata ) {
	
	$list_id = 'YOUR AUDIENCE ID';
	$api = 'YOUR API KEY';
	
	// user data
	$email = $old_userdata->user_email;
	// we can user's first and last names directly from WP_User object
	$first_name = $userdata->first_name;
	$last_name = $userdata->last_name;
	// but we can also obtain some information from metadata like this
	$city = get_user_meta( $user_id, 'city', true );
	
	wp_remote_request( 
		'https://' . substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email)),
		array(
			'method' => 'PATCH',
		 	'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
			),
			'body' => json_encode(
				array(
					'merge_fields' => array( 
						'FNAME' => $first_name, 
						'LNAME' => $last_name,
						'CITY' => $city,
					)
				)
			)
		)
	);

}, 25, 3 );

And now just a little bit of explanation how it works:

Mailchimp audience fields settings
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 X