Your cart is currently empty!
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.
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;
} );
Instructions for Download a MailChimp contact list to CSV
- Log into a staging or locally hosted clone of your site.
- Install and activate Code Snippets plugin.
- WP Admin > Snippets > Add New
- Copy and paste the code from the section above.
- Check to ensure formatting came over properly.
- 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.
Need help modifying Download a MailChimp contact list to CSV?
Contact me. I can help with fitting projects or refer to my partner.
License
All code snippets are licensed GPLv2 (or later) matching WordPress licensing.
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.
Disclaimer of warranty