Skip to content

Instantly share code, notes, and snippets.

@kovshenin
Created November 19, 2015 13:03
Show Gist options
  • Save kovshenin/18892578342132f88b8b to your computer and use it in GitHub Desktop.
Save kovshenin/18892578342132f88b8b to your computer and use it in GitHub Desktop.
Get subscribers count via the MailChimp API.
<?php
/**
* Get subscribers count via the MailChimp API.
*/
function mailchimp_get_subscribers_count() {
$cache_key = 'mailchimp-subscribers';
$api_key = '';
$username = '';
$dc = '';
$list_id = '';
$count = get_transient( $cache_key );
if ( $count === false ) {
$count = 0;
$url = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}";
$request = wp_remote_get( $url, array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $api_key ),
),
) );
if ( wp_remote_retrieve_response_code( $request ) == 200 ) {
$body = wp_remote_retrieve_body( $request );
$body = json_decode( $body, true );
$count = absint( $body['stats']['member_count'] );
}
set_transient( $cache_key, $count, 12 * HOUR_IN_SECONDS );
}
return $count;
}
@LinuxEvangelist
Copy link

Hi, I write this code maybe will help.

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "http://usXX.api.mailchimp.com/3.0/lists/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: XXXXXXXXXXXXXXXXX",
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
$a = json_decode($response,true);
$sumcount = 0;
foreach($a['lists'] as $v){
$sumcount+= $v['stats']['member_count'];
}

echo $sumcount;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment