Learn How To Use MailChimp API In WordPress Plugin

Malika Rani

There are a number of email marketing tools available to optimize email campaigns. MailChimp is one among the popular email marketing service which make it easy to design and share email campaigns, manage your subscribers lists, and track results.

Also read..

MailGet – Bulk Email Marketing Service affordable and highly reliable. MailGet has API to collect emails and send automatic emails. 

In this tutorial, I will make you understand how you can retrieve lists that you have already created under your MailChimp account using MailChimp API key. And, how you can add subscribers in that lists in WordPress plugin.

Get the mailchimp list data

Steps To Retrieve List Of The MailChimp

You can create as many lists as you need in your MailChimp account.

As you can see in the below image, there are 3 lists created and appears in the MailChimp account.

Now with the help of below code, you can retrieve these lists i.e. their names and respective id’s.

create list

Below piece of code requires your MailChimp account API key. So to get the API key, you need to follow the below steps.

Go to Account Settings

Account settings

Go to Extras –> API keys

Get the API key

You can see your MailChimp API keys here, copy this API key and enter it in the below code.

API key revealed

Additionally, it is very necessary to include library for MailChimp PHP API. So you can download MailChimp API PHP Class and integrate it into your projects.

As I have already downloaded and save it in the file named, MCAPI.class.php, so you can directly use the below code.

class MCAPI {
var $version = "1.3";
var $errorMessage;
var $errorCode;

* Cache the information on the API location on the server
var $apiUrl;

* Default to a 300 second timeout on server calls
var $timeout = 300;

* Default to a 8K chunk size
var $chunkSize = 8192;

* Cache the user api_key so we only have to log in once per client instantiation
var $api_key;

* Cache the user api_key so we only have to log in once per client instantiation
var $secure = false;

* Connect to the MailChimp API for a given list.
* @param string $apikey Your MailChimp apikey
* @param string $secure Whether or not this should use a secure connection
function MCAPI($apikey, $secure=false) {
$this->secure = $secure;
$this->apiUrl = parse_url("http://api.mailchimp.com/" . $this->version . "/?output=php");
$this->api_key = $apikey;
function setTimeout($seconds){
if (is_int($seconds)){
$this->timeout = $seconds;
return true;
function getTimeout(){
return $this->timeout;
function useSecure($val){
if ($val===true){
$this->secure = true;
} else {
$this->secure = false;

* Actually connect to the server and call the requested methods, parsing the result
* You should never have to call this function manually
function __call($method, $params) {
$dc = "us1";
if (strstr($this->api_key,"-")){
list($key, $dc) = explode("-",$this->api_key,2);
if (!$dc) $dc = "us1";
$host = $dc.".".$this->apiUrl["host"];

$this->errorMessage = "";
$this->errorCode = "";
$sep_changed = false;
//sigh, apparently some distribs change this to &amp; by default
if (ini_get("arg_separator.output")!="&"){
$sep_changed = true;
$orig_sep = ini_get("arg_separator.output");
ini_set("arg_separator.output", "&");
//mutate params
$mutate = array();
$mutate["apikey"] = $this->api_key;
foreach($params as $k=>$v){
$mutate[$this->function_map[$method][$k]] = $v;
$post_vars = http_build_query($mutate);
if ($sep_changed){
ini_set("arg_separator.output", $orig_sep);

$payload = "POST " . $this->apiUrl["path"] . "?" . $this->apiUrl["query"] . "&method=" . $method . " HTTP/1.0\r\n";
$payload .= "Host: " . $host . "\r\n";
$payload .= "User-Agent: MCAPImini/" . $this->version ."\r\n";
$payload .= "Content-type: application/x-www-form-urlencoded\r\n";
$payload .= "Content-length: " . strlen($post_vars) . "\r\n";
$payload .= "Connection: close \r\n\r\n";
$payload .= $post_vars;

if ($this->secure){
$sock = fsockopen("ssl://".$host, 443, $errno, $errstr, 30);
} else {
$sock = fsockopen($host, 80, $errno, $errstr, 30);
if(!$sock) {
$this->errorMessage = "Could not connect (ERR $errno: $errstr)";
$this->errorCode = "-99";
return false;

$response = "";
fwrite($sock, $payload);
stream_set_timeout($sock, $this->timeout);
$info = stream_get_meta_data($sock);
while ((!feof($sock)) && (!$info["timed_out"])) {
$response .= fread($sock, $this->chunkSize);
$info = stream_get_meta_data($sock);
if ($info["timed_out"]) {
$this->errorMessage = "Could not read response (timed out)";
$this->errorCode = -98;
return false;

list($headers, $response) = explode("\r\n\r\n", $response, 2);
$headers = explode("\r\n", $headers);
$errored = false;
foreach($headers as $h){
if (substr($h,0,26)==="X-MailChimp-API-Error-Code"){
$errored = true;
$error_code = trim(substr($h,27));

if(ini_get("magic_quotes_runtime")) $response = stripslashes($response);

$serial = unserialize($response);
if($response && $serial === false) {
$response = array("error" => "Bad Response. Got This: " . $response, "code" => "-99");
} else {
$response = $serial;
if($errored && is_array($response) && isset($response["error"])) {
$this->errorMessage = $response["error"];
$this->errorCode = $response["code"];
return false;
} elseif($errored){
$this->errorMessage = "No error message was found";
$this->errorCode = $error_code;
return false;

return $response;

protected $function_map = array('campaignUnschedule'=>array("cid"),


Now, create a new file let say, demo.php and save this file under the same folder where you have saved the MCAPI.class.php file.

Note: I have created a new folder named MailChimp that contain above files and that I saved it under the www folder of wamp server.

require_once 'MCAPI.class.php';
$apikey='Your-MailChimp-API-Key'; // Enter your MailChimp API key here
$api = new MCAPI($apikey);
$retval = $api->lists();
foreach ($retval['data'] as $list){
echo $list['name']; echo "&nbsp"; echo "&nbsp"; echo "&nbsp"; echo "&nbsp"; echo "&nbsp";
echo $list['id'];
echo "<br />";

When you run the demo.php file, this is how the output appears.

list name with ids

Steps To Add Subscriber Name And Email Address In The List

As you see in the above output window, lists names with their respective id’s are shown.

Now you can easily add subscriber name and email address in the list using list id’s.

In below image, you can see the list named Trail_List under MailChimp account contain only 1 subscriber.

user data on mailchimp dashboard

Now using below code, you can add the subscriber name and email address to the respective list. For that, you need to provide the list id where you want to add a subscriber.

require_once 'MCAPI.class.php';
$apikey='Your-API-Key'; // Enter your API key
$api = new MCAPI($apikey);
$retval = $api->lists();
$listid='List-Id'; // Enter list Id here
$email='Subscriber-email-address'; // Enter subscriber email address
$name='Subscriber-first-name'; // Enter subscriber first name
$lname='Subscriber-last-name'; // Enter subscriber last name

// By default this sends a confirmation email - you will not see new members
// until the link contained in it is clicked!

$merge_vars = array('FNAME' => $name, 'LNAME' => $lname);
if($api->listSubscribe($listid, $email,$merge_vars) === true) {
echo 'success';

As soon as you execute the above code, subscriber will be notify to their respective email address. Subscriber need to confirm it by clicking on to the Yes, subscribe me to this list. button

confirm subscription url

The below window opens after confirming the subscription.

subscription confirmed notification

Now see the Trail_List, name of the newly added subscriber appears in the list.

subscriber data on dashboard


I hope above code make it easy to use MailChimp API in WordPress plugin. But in case, you find any difficulty then let me know in the below comment section. I will definitely help you out. Please share your thoughts about the post too.

Last Updated on: June 6, 2017

Under: ,

Comments and Responses

Your email address will not be published. Required fields are marked *