Skip to content

Instantly share code, notes, and snippets.

@brianjking
Forked from kovshenin/subscribers-count.php
Created July 19, 2018 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianjking/a1c251bb13546e892652d09f01b5f502 to your computer and use it in GitHub Desktop.
Save brianjking/a1c251bb13546e892652d09f01b5f502 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment