Sync WooCommerce Customers Between Stores

We already know from my previous tutorial how you can sync WordPress users between sites using REST API. And I also have a plugin for that. But today we are going to make it a little bit differently – for WooCommerce customers using WooCommerce REST API.

Once again I have plenty of tutorials about WooCommerce REST API on my blog, so those who already had a chance to work with it, they will learn nothing new here, I guess.

Indeed, the example in this tutorial is quite simple – we are going to go to any user profile settings, hit “Update User” button and we expect those changes to be reflected on the other WooCommerce store. As simple as that.

add_action( 'profile_update', 'rudr_update_woo_customer', 25, 3 );

function rudr_update_woo_customer( $user_id, $old_userdata, $userdata ) {

	$url = '';
	$login = '';
	$pwd = '';

	// get user ID first
	$request = wp_remote_get( add_query_arg( 'slug', $userdata->user_nicename, "{$url}/wp-json/wp/v2/users" ) );

	// we didn't find users or couldn't connect – exit on that
	if( 'OK' !== wp_remote_retrieve_response_message( $request ) ) {
		return;
	}

	$remote_users = json_decode( wp_remote_retrieve_body( $request ) );
	if( ! $remote_users ) {
		return;
	}

	$remote_user = reset( $remote_users );

	// now it is time to update it WooCommerce-way
	if( ! class_exists( 'WC_Customer' ) ) {
		return; // WooCommerce is not installed, just to prevent fatal errors
	}

	$customer = new WC_Customer( $user_id );
	$customer_data = $customer->get_data();
	// we can unset some unnecessary things here
	unset( $customer_data[ 'id' ] );
	// maybe you don't want to change main user email (it is not a billing or shipping one)
	unset( $customer_data[ 'email' ] );
	
	wp_remote_request(
		"{$url}/wp-json/wc/v3/customers/{$remote_user->id}",
		array(
			'method' => 'PUT',
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "{$login}:{$pwd}" )
			),
			'body' => $customer_data
		)
	);

}
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