add_action( 'admin_init', function() {
// Settings
$api_key = 'API_KEY_HERE';
$list_id = 'LIST_ID_HERE';
// Set Variables
$dc = substr( $api_key, strpos( $api_key, '-' ) + 1 );
$url = 'https://' . $dc . '.api.mailchimp.com/3.0/lists/' . $list_id;
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
)
);
// Get List Information
$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 ) { return; }
// Get List Members In Batches Of Fifty
$member_count = $body->stats->member_count;
$rows = [];
for( $offset = 0; $offset < $member_count; $offset += 50 ) {
$response = wp_remote_get(
'https://' . $dc . '.api.mailchimp.com/3.0/lists/'
. $list_id . '/members?offset=' . $offset . '&count=50',
$args
);
$body = json_decode( $response['body'] );
if( $response['response']['code'] == 200 ) {
foreach( $body->members as $member ) {
$rows[] = [
$member->email_address,
$member->merge_fields->FNAME,
$member->merge_fields->LNAME,
];
}
}
}
// Output As Downloadable CSV
header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment; filename=download.csv' );
$out = fopen( 'php://output', 'w' );
foreach( $rows as $row ) {
fputcsv( $out, $row );
}
fclose( $out );
exit;
} );
Download a MailChimp contact list to CSV
Downloads the subscribers of a single MailChimp contact list given the API key and List ID. CSV format.
Set this as a Run Once type code snippet.
How to use
- Log into a staging, development, or locally hosted clone of your site
- Install and activate Code Snippets
- WP Admin > Snippets > Add New
- Copy and paste the code from the Description tab above
- Check to ensure formatting came over properly and no syntax errors show up in the editor
- Customize the code as desired
- Add a meaningful title
- Select whether to run on front-end or back-end (or both)
- Click “Save and Activate”
- Test your site to ensure it works
- Disable if any problems, or recover
- Repeat for live environment
License
All code snippets are licensed GPLv2 (or later) matching WordPress licensing.
Disclaimer of warranty:
Except when otherwise stated in writing the copyright holders and/or other parties provide the program as-is without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.
Support
- Describe the issue and what you’ve observed.
- Describe your expected outcome(s).
- List steps to reproduce the issue.
- Optionally provide screen-shot or video URLs.
