MailChimp API 3.0 and WordPress HTTP API

Easy way to connect MailChimp API using WordPress default wp_remote_get() and wp_remote_post() functions.

#httpapi, #mailchimp  /  July 5, 2016  /   1

For MailChimp API connection I always used this function. So, if you need non-WordPress examples, please go there. But in this post I will show you more simpler way to connect MailChimp API via WordPress HTTP API functions – wp_remote_get() and wp_remote_post().

wp_remote_get()

You can use wp_remote_get() function for any API requests that requires GET method. That’s what I mean:

GET methods in MailChhimp API

Get list subscribers count

In this example we will get all the information about a specific list in MailChimp and list subscribers count accordingly.

Read where to get your API key and a list ID.

$api_key = 'YOUR API KEY';
$list_id = 'YOUR LIST ID';
$dc = substr($api_key,strpos($api_key,'-')+1); // datacenter, it is the part of your api key - us5, us8 etc
$args = array(
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
	)
);
 
$response = wp_remote_get( 'https://'.$dc.'.api.mailchimp.com/3.0/lists/'.$list_id, $args );
 
$body = json_decode( $response['body'] );
 
if ( $response['response']['code'] == 200 ) {
	echo $body->stats->member_count;
} else {
	echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
}

Get all subscribers emails from a list

In this table you can see some another WordPress HTTP API functions and their equivalents. You can use them or not – as you want.

Direct usage WordPress function
$response['response']['code'] wp_remote_retrieve_response_code( $response )
$response['body'] wp_remote_retrieve_body( $response )
$response['response']['message'] wp_remote_retrieve_response_message( $response )
$api_key = 'YOUR API KEY';
$list_id = 'YOUR LIST ID';
$dc = substr($api_key,strpos($api_key,'-')+1); // us5, us8 etc
$args = array(
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
	)
);
$response = wp_remote_get( 'https://'.$dc.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members/', $args );
$body = json_decode( wp_remote_retrieve_body( $response ) );
$emails = array();
 
if ( wp_remote_retrieve_response_code( $response ) == 200 ) {
	foreach ( $body->members as $member ) {
		if( $member->status != 'subscribed' )
			continue;
		$emails[] = $member->email_address;
	}
	print_r( $emails );
} else {
	echo '<b>' . wp_remote_retrieve_response_code( $response ) . wp_remote_retrieve_response_message( $response ) . ':</b> ' . $body->detail;
}

wp_remote_post()

Function wp_remote_post() can be used for POST, PUT, PATCH and DELETE API calls. Some examples are on the screenshot:

PUT, POST, PATCH, DELETE API methods in MailChimp

If I forgot about something, please let me know in comments.

Subscribe or unsubscribe user

The very popular function – let’s look how to implement it easily using wp_remote_post().

$api_key = 'YOUR API KEY';
$email = 'USER EMAIL';
$status = 'unsubscribed'; // subscribed, cleaned, pending
 
$args = array(
	'method' => 'PUT',
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
	),
	'body' => json_encode(array(
    		'email_address' => $email,
		'status'        => $status
	))
);
$response = wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email)), $args );
 
$body = json_decode( $response['body'] );
 
if ( $response['response']['code'] == 200 && $body->status == $status ) {
	echo 'The user has been successfully ' . $status . '.';
} else {
	echo '<b>' . $response['response']['code'] . $body->title . ':</b> ' . $body->detail;
}

Delete list members

If you want just to set status unsubscribed or cleaned for you subscriber – look at the previous example. But if you want to completely remove user email from a list, this code is for you then:

$api_key = 'YOUR API KEY';
$list_id = 'YOUR LIST ID';
$email = 'USER EMAIL';
 
$args = array(
	'method' => 'DELETE',
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
	)
);
 
wp_remote_post( 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email)), $args );

Batch subscribe all users with a specific role

There are not much examples of MailChimp batch operations over the web, but your can find another one on this website here.

$api_key = 'YOUR API KEY SHOULD BE HERE';
$list_id = 'YOUR LIST ID';
$dc = substr($api_key,strpos($api_key,'-')+1);
 
 
// "Schema describes object"? Not a problem
$body_args = new stdClass();
// all the batch operations will be stored in this array
$body_args->operations = array();
 
$wordpress_users_all = get_users( 'role=subscriber' ); // you may add another parameters into this function
 
// loop all found WP users
 
foreach ( $wordpress_users_all as $user ) {
	// a single batch operation object for each user
	$batch =  new stdClass();
	$batch->method = 'PUT';
	$batch->path = 'lists/' . $list_id . '/members/' . md5(strtolower($user->user_email));
	$batch->body = json_encode( array(
		'email_address' => $user->user_email,
		'status'        => 'subscribed',
		'merge_fields'  => array( 
			'FNAME' => $user->first_name,
			'LNAME' => $user->last_name
		)
	) );
	$body_args->operations[] = $batch;
}
 
$args = array(
	'method' => 'POST',
 	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
	),
	'body' => json_encode( $body_args )
);
 
$response = wp_remote_post( 'https://'.$dc.'.api.mailchimp.com/3.0/batches', $args );
 
$body = json_decode( wp_remote_retrieve_body( $response ) );
echo $body->id;

$body->id is the batch operation ID, try to get the status of a batch operation by yourself using wp_remote_get() and this API endpoint /batches/{batch_id}.

If you need more functionality, try to use my plugin, it allows to synchronize your WordPress users with MailChimp lists.
Download WordPress plugin

Only the best of WordPress

once a week, no spam

Comments 1

  • I was just wondering when WordPress supports HTTP API MailChimp API can be implemented using it.
    Thanks for sharing this.

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email