Mailchimp API in WordPress

In this tutorial we are going to talk deeply about establishing connection with Mailchimp API using WordPress HTTP API functions.

In our code examples we are going to use wp_remote_get(), wp_remote_post() and wp_remote_request() functions. If you’re looking for cURL examples, here is another tutorial.

In 2016 I developed Simple Mailchimp Sync plugin that allows to sync your WordPress users with specific Mailchimp audiences. I continue supporting and developing this plugin. So, I have some experience with Mailchimp API guys.

How to Use Mailchimp API in WordPress?

Before we dive into actual examples, let’s figure out some basics.

Mailchimp APIs

First things first, Mailchimp Marketing API is available by this link. There is also transactional API, here is the link.

What WordPress HTTP API function to use?

Second, we have to figure out what WordPress HTTP API function we have to use for our specific task. As I mentioned before, there are three of them – wp_remote_get(), wp_remote_post() and wp_remote_request(). Actually you can use any of them for any request, but in order to make our code more beautiful and clear, we are going to use wp_remote_get() for GET requests, wp_remote_post() – for POST requests and wp_remote_request() for PUT, PATCH and DELETE requests.

Let’s take a look at the screenshot.

Mailchimp API audiences
You can see a request type in pink color. So, in order to get lists info we will use wp_remote_get() function, in order to add a list – wp_remote_post() and if we want to delete a specific list – wp_remote_request() function will help us with that.

Where to get Mailchimp API key?

For every API request we will need an API key. I already described where you can get it here.

Create a HTTP API request

Now let’s use a screenshot above and create a request. Let’s begin with the simplest one.

$response = wp_remote_get( 
	'https://'. substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/lists/', 
	array(
 		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
		)
	)
);

Some moments I would like to highlight in this code:

  • In every example $api variable is our API key we should specify before in the code.
  • As you can see API key is used not only for basic authorization, but also as part of a request URL, so your URL will start with something like https://us14.api.mailchimp.com... or https://us5.api.mailchimp... etc.

Pass parameters to a HTTP request

If you check the documentation of /lists, you can find out that by default it returns only the last 10 audiences. But what if you need more? Let’s for example get at least 100 audiences per request? So we have to specify it in count parameter (according to API docs). Parameters can be passed in the body of the request as a JSON-encoded array.

$response = wp_remote_get( 
	'https://'. substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/lists/', 
	array(
 		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
		),
		'body' => json_encode( 
			array(
    			'count' => 100
			)
		)
	)
);

Process the response data

Once the request has been made, the main work is usually finished – maybe a specific email is subscribed to a specific audience, maybe a specific audience has been removed – I don’t know what you’re doing. But usually we have to get the information about the finished request. In our case – we are going to print the Mailchimp audiences as an <ul> list.

WordPress functions wp_remote_retrieve_response_code(), wp_remote_retrieve_body(), wp_remote_retrieve_response_message() are intended to help us. It is not 100% necessary to use any of them actually. You can print_r( $response ) and you will find out why. But I prefer to use them in order to make my code clean and readable.

Direct usageWordPress 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 )

Example:

if( 'OK' === wp_remote_retrieve_response_message( $response ) ) {
// if( 200 === wp_remote_retrieve_response_code( $response ) ) {
	$body = json_decode( wp_remote_retrieve_body( $response ) );
	if( $body->lists ) {
		echo '<ul>';
		foreach( $body->lists as $list ) {
			echo "<li>{$list->name} ({$list->stats->member_count})</li>";
		}
		echo '</ul>';
	}
} else {
	echo 'The request failed.';	
}

Mailchimp API Examples

Get list subscribers count

In this example we will get all the information about a specific audience (list) in Mailchimp and its subscribers count. You will also need an audience ID, how to get it I described here.

$list_id = 'YOUR AUDIENCE ID';

$response = wp_remote_get( 
	'https://' . substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id,
	array(
	 	'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
		)
	)
);

if ( 200 == wp_remote_retrieve_response_code( $response ) ) {
	$body = json_decode( wp_remote_retrieve_body( $response ) );
	echo 'Subscribers:' . $body->stats->member_count;
}

Get all subscriber emails from a specific audience

We continue to work with GET requests, so we’re still using wp_remote_get() function.

$list_id = 'YOUR AUDIENCE ID';

$response = wp_remote_get( 
	'https://' . substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/', 
	array(
	 	'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
		)
	)
);

if( 200 === wp_remote_retrieve_response_code( $response ) ) {
	$emails = array();
	$body = json_decode( wp_remote_retrieve_body( $response ) );
	foreach( $body->members as $member ) {
		if( 'subscribed' !== $member->status ) {
			continue;
		}
		$emails[] = $member->email_address;
	}
	print_r( $emails );
}

Subscribe or unsubscribe a user

$list_id = 'YOUR AUDIENCE ID';

$response = wp_remote_request( 
	'https://' . substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email)),
	array(
		'method' => 'PUT',
	 	'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
		),
		'body' => json_encode(
			array(
				'email_address' => 'no-reply@rudrastyh.com', // change the email here
				'status' => 'subscribed' // unsubscribed, pending
			)
		)
	)
);

if( 'OK' === wp_remote_retrieve_response_message( $response ) ) {
	echo 'The user has been successfully subscribed.';
}

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 a specific user email from a list, this code is for you then:

wp_remote_request(
	'https://' . substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email)),
	array(
		'method' => 'DELETE',
	 	'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
		)
	)
);

Batch subscribe all users with a specific role

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

// "Schema describes object"? Not a problem
$args = new stdClass();
// all the batch operations will be stored in this array
$args->operations = array();
 
$users = get_users( 'role=subscriber' );
if( $users ) {
	foreach( $users 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
				)
			)
		);
		$args->operations[] = $batch;
	}
}

$response = wp_remote_post( 
	'https://' . substr($api,strpos($api,'-')+1) . '.api.mailchimp.com/3.0/batches', 
	array(
		'method' => 'POST',
	 	'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( 'user:'. $api )
		),
		'body' => json_encode( $body_args )
	)
);

$body = json_decode( wp_remote_retrieve_body( $response ) );
echo $body->id;

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

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