Misha Rudrastyh

Misha Rudrastyh

WordPress Developer

MailChimp API 3.0 – Subscribe your WordPress users automatically

In this tutorial I will show you how to subscribe new and previously registered WordPress users to a MailChimp list automatically. Without plugins.

June 14, 2016 Leave comment

The code below works the same for every user role (for subscribers and administrators, for editors and authors etc). But if you want to subscribe each user role to a different MailChimp list, you should take a look at my plugin.

I think it is very easy tutorial because all you need is to copy the code from here and insert it to your theme functions.php. The only thing you have to change in this code is your MailChimp API key and MailChimp List ID you want to subscribe your website users to.

  • Do not you know where to obtain MailChimp API key? This small tutorial will help you.
  • Do not you know where to get a list ID? Read here.

Step 1. MailChimp API connection using PHP

cURL connection function

In my previous tutorial I created the universal function for connection to MailChimp API via cURL. This is the first step — insert this function without changing anything in it to your current theme functions.php.

Subscription/unsubscription function

The next function will allows us to subscribe or unsubscribe the users.

function rudr_mailchimp_subscribe_unsubscribe( $email, $status, $merge_fields = array( 'FNAME' => '', 'LNAME' => '' ) ){
	 * please provide the values of the following variables 
	 * do not know where to get them? read above
	$list_id = 'YOUR LIST ID HERE';
	/* MailChimp API URL */
	$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email));
	/* MailChimp POST data */
	$data = array(
		'apikey'        => $api_key,
    		'email_address' => $email,
		'status'        => $status, // in this post we will use only 'subscribed' and 'unsubscribed'
		'merge_fields'  => $merge_fields // in this post we will use only FNAME and LNAME
	return json_decode( rudr_mailchimp_curl_connect( $url, 'PUT', $api_key, $data ) );

One important notice about merge_fields array — if your WordPress registration doesn’t require First name and Last name of the user, make sure, that these merge fields are set to optional.

Optional First name (FNAME) and Last name (LNAME) merge fields in MailChimp list settings.

In MailChimp dashboard you can find it in list settings in List fields and *|MERGE|* tags.

Step 2. Subscribe a user to a specific MailChimp list after his registration on your WordPress website

Hook user_register in WordPress will be fired:

  • when a user is registered himself on the website,
  • when administrators register a user via admin area Users > Add New,
  • when user is registered via a function, for example wp_insert_user() or wp_create_user().
add_action('user_register', 'rudr_user_register_hook', 20, 1 );
function rudr_user_register_hook( $user_id ){
	$user = get_user_by('id', $user_id ); // feel fre to use get_userdata() instead
	$subscription = rudr_mailchimp_subscribe_unsubscribe( $user->user_email, 'subscribed', array( 'FNAME' => $user->first_name,'LNAME' => $user->last_name ) );
	 * if user subscription was failed you can try to store the errors the following way
	if( $subscription->status != 'subscribed' )
		update_user_meta( $user_id, '_subscription_error', 'User was not subscribed because:' . $subscription->detail );

Change user subscription status from subscribed to pending if you want to send confirmation emails.

Please note, that new subscribers will appear in your MailChimp dashboard not immediately but within a couple of minutes.

Step 3. Unsubscribe a user if he was removed from the website

Action hook delete_user will be fired if user was removed from the website in admin area by administrators or in the code by wp_delete_user() function.

Actually this action hook is fired immediately before a user is deleted from the database, that’s why you can still get the user’s data like email, first name etc.

add_action( 'delete_user', 'rudr_user_delete_hook', 20, 1 );
function rudr_user_delete_hook( $user_id ){
	$user = get_user_by( 'id', $user_id );
	$subscription = rudr_mailchimp_subscribe_unsubscribe( $user->user_email, 'unsubscribed', array( 'FNAME' => $user->first_name,'LNAME' => $user->last_name ) );

Step 4. Batch Subscribe Previously Registered Users

But what if you want to subscribe all previously registered users as well? Do you think it is good idea to run the loop of users with rudr_mailchimp_subscribe_unsubscribe() function in it? Of course it isn’t, please don’t do that!

You do not have to open a cURL connection for each WordPress user (what if there are 1000 users on your website?!). MailChimp batch operations allows to do this just in a single connection.

You may not believe me but I didn’t find a working PHP implementation of MailChimp 3.0 batch operations around the web at all. At all!

And here is my example. You can insert the following code to functions.php file as well but run it only once!

function rudr_batch_wp_users_subscribe() {
	$list_id = 'YOUR LIST ID HERE';
	/* MailChimp API URL */
	$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/batches';
	// "Schema describes object"? Not a problem
	$data = new stdClass();
	// all the batch operations will be stored in this array
	$data->operations = array();
	$wordpress_users_all = get_users( 'exclude=1' ); // if you do not want to subscribe yourself (but maybe you have another user ID)
	// loop all WP users
	foreach ( $wordpress_users_all as $user ) {
		// a single batch operation object for each user
		$batch =  new stdClass();
		$batch->method = 'POST';
		$batch->path = 'lists/' . $list_id . '/members';
		$batch->body = json_encode( array(
			'email_address' => $user->user_email,
			'status'        => 'subscribed',
			'merge_fields'  => array( 
				'FNAME' => $user->first_name,
				'LNAME' => $user->last_name
		) );
		$data->operations[] = $batch;
	return json_decode( rudr_mailchimp_curl_connect( $url, 'POST', $api_key, $data ) );

Get a batch operation status

The following function returns all information about an operation with the exact ID. You can just prinit_r() it.

function rudr_get_batch_by_id( $batch_id ) {
	$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/batches/' . $batch_id;
	return json_decode( rudr_mailchimp_curl_connect( $url, 'GET', $api_key ) );

Ready to use WordPress plugin with much more MailChimp Synchronization Options

Want to subscribe users to different MailChimp lists depending on user roles? Want to integrate MailChimp with WooCommerce Memberships? This plugin can help you.
Download the plugin

Only new posts about WordPress

once a week

Leave comment

Please, enter a comment
Please, enter a name
Incorrect email
© 2016 Misha Rudrastyh
Developed on with