MailChimp API 3.0 – Subscribe your WordPress users automatically
The code below works the same for every user role (for subscribers and administrators, for editors and authors etc). But if you want to subscribe each user role to a different MailChimp list, you should take a look at my plugin.
I think it is very easy tutorial because all you need is to copy the code from here and insert it to your theme functions.php
. The only thing you have to change in this code is your MailChimp API key and MailChimp List ID you want to subscribe your website users to.
- Do not you know where to obtain MailChimp API key? This small tutorial will help you.
- Do not you know where to get a list ID? Read here.
Step 1. MailChimp API connection using PHP
cURL connection function
In my previous tutorial I created the universal function for connection to MailChimp API via cURL. This is the first step — insert this function without changing anything in it to your current theme functions.php
.
Subscription/unsubscription function
The next function will allows us to subscribe or unsubscribe the users.
function rudr_mailchimp_subscribe_unsubscribe( $email, $status, $merge_fields = array( 'FNAME' => '', 'LNAME' => '' ) ){
/*
* please provide the values of the following variables
* do not know where to get them? read above
*/
$api_key = 'YOUR API KEY SHOULD BE HERE';
$list_id = 'YOUR LIST ID HERE';
/* MailChimp API URL */
$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($email));
/* MailChimp POST data */
$data = array(
'apikey' => $api_key,
'email_address' => $email,
'status' => $status, // in this post we will use only 'subscribed' and 'unsubscribed'
'merge_fields' => $merge_fields // in this post we will use only FNAME and LNAME
);
return json_decode( rudr_mailchimp_curl_connect( $url, 'PUT', $api_key, $data ) );
}
One important notice about merge_fields
array — if your WordPress registration doesn’t require First name and Last name of the user, make sure, that these merge fields are set to optional.
In MailChimp dashboard you can find it in list settings in List fields and *|MERGE|* tags.
Step 2. Subscribe a user to a specific MailChimp list after his registration on your WordPress website
Hook user_register
in WordPress will be fired:
- when a user is registered himself on the website,
- when administrators register a user via admin area Users > Add New,
- when user is registered via a function, for example
wp_insert_user()
orwp_create_user()
.
add_action('user_register', 'rudr_user_register_hook', 20, 1 );
function rudr_user_register_hook( $user_id ){
$user = get_user_by('id', $user_id ); // feel fre to use get_userdata() instead
$subscription = rudr_mailchimp_subscribe_unsubscribe( $user->user_email, 'subscribed', array( 'FNAME' => $user->first_name,'LNAME' => $user->last_name ) );
/*
* if user subscription was failed you can try to store the errors the following way
*/
if( $subscription->status != 'subscribed' )
update_user_meta( $user_id, '_subscription_error', 'User was not subscribed because:' . $subscription->detail );
}
Change user subscription status from subscribed
to pending
if you want to send confirmation emails.
Please note, that new subscribers will appear in your MailChimp dashboard not immediately but within a couple of minutes.
Step 3. Unsubscribe a user if he was removed from the website
Action hook delete_user
will be fired if user was removed from the website in admin area by administrators or in the code by wp_delete_user()
function.
Actually this action hook is fired immediately before a user is deleted from the database, that’s why you can still get the user’s data like email, first name etc.
add_action( 'delete_user', 'rudr_user_delete_hook', 20, 1 );
function rudr_user_delete_hook( $user_id ){
$user = get_user_by( 'id', $user_id );
$subscription = rudr_mailchimp_subscribe_unsubscribe( $user->user_email, 'unsubscribed', array( 'FNAME' => $user->first_name,'LNAME' => $user->last_name ) );
}
Step 4. Batch Subscribe Previously Registered Users
But what if you want to subscribe all previously registered users as well? Do you think it is good idea to run the loop of users with rudr_mailchimp_subscribe_unsubscribe()
function in it? Of course it isn’t, please don’t do that!
You do not have to open a cURL connection for each WordPress user (what if there are 1000 users on your website?!). MailChimp batch operations allows to do this just in a single connection.
You may not believe me but I didn’t find a working PHP implementation of MailChimp 3.0 batch operations around the web at all. At all!
And here is my example. You can insert the following code to functions.php
file as well but run it only once!
function rudr_batch_wp_users_subscribe() {
$api_key = 'YOUR API KEY SHOULD BE HERE';
$list_id = 'YOUR LIST ID HERE';
/* MailChimp API URL */
$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/batches';
// "Schema describes object"? Not a problem
$data = new stdClass();
// all the batch operations will be stored in this array
$data->operations = array();
$wordpress_users_all = get_users( 'exclude=1' ); // if you do not want to subscribe yourself (but maybe you have another user ID)
// loop all WP users
foreach ( $wordpress_users_all as $user ) {
// a single batch operation object for each user
$batch = new stdClass();
$batch->method = 'POST';
$batch->path = 'lists/' . $list_id . '/members';
$batch->body = json_encode( array(
'email_address' => $user->user_email,
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $user->first_name,
'LNAME' => $user->last_name
)
) );
$data->operations[] = $batch;
}
return json_decode( rudr_mailchimp_curl_connect( $url, 'POST', $api_key, $data ) );
}
Get a batch operation status
The following function returns all information about an operation with the exact ID. You can just prinit_r()
it.
function rudr_get_batch_by_id( $batch_id ) {
$api_key = 'YOUR API KEY SHOULD BE HERE';
$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/batches/' . $batch_id;
return json_decode( rudr_mailchimp_curl_connect( $url, 'GET', $api_key ) );
}
Ready to use WordPress plugin with much more MailChimp Synchronization Options
Want to subscribe users to different MailChimp lists depending on user roles? Want to integrate MailChimp with WooCommerce Memberships? This plugin can help you.

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me
Thanks for your code, it works great! However when a user is already registered to the website, there’a a way to update his data on mailchimp if they change their first name or last name from woocommerce my_account page or when they add more data like address and phone during the checkout?
Hi Tom,
Simple subscribe method works just great, for WordPress you can find a well described example here.
But in case you would like just update user, not add him, use
PATCH
method instead ofPUT
(that’s all you need to change).Thanks! works like a charme (as usual) :)
Just another question: you use this action
to hook the function and send data to Mailchimp when a user registered himself on the website.
I successfully hooked your function in my_account page to update Mailchimp when a user change their data using this action:
.
I supposed to do the same in the checkout page when a user confirm his purchase but unfortunately I can’t find any hook to perform this. Do you know have any ideas? Thanks a lot!
Tom
Did you try hooks like this
woocommerce_order_status_{order status}
?It works! Thanks!
Wow, thank you so much for this script !! Very helpful !
And what if I want to add or update tags ? I tried to add a $tags_array in the $data, but it doesn’t work, can you help me, please ?
Hi Nathalie,
Do you mean merge fields? or.. ?
Thanks for your reply !
I need to add tags to the subscribers’ profile and it seems you can’t add them in the merge fields or I don’t know how I have to do that. I tried to add an array “TAGS => array(“tag1″ => value1”, “tage2” => value 2 etc, but it returned null
Otherwise I could add interests but I also don’t know how…
(I’m talking about the tags you can add at the end of the form when you add a subscriber manually on MC website)
Did you try to use an array key
merge_fields
instead ofTAGS
?I already have a merge_fields array, to send the details of the subscriber, but I need to add an array tags too and I don’t know how to proceed. When I add the tags into the the merge_fields, I get an error
Did you try this?
Is it possible to sync users without First and Last name, as my form doesn’t have it?
Thanks!
Hey,
Yes, both first name and last name are optional
Maybe because I use https://www.easyregistrationforms.com/ I can’t make it work on custom registration form. You can contact by email if you could try to customize it for me, and tell me what would cost me?
Daft question…Where does Batch_Id come from? :)
In Step 4 in what function returns :)
Hi Misha, thank you for this. It’s fabulous. Question. This seems to work when I subscribe someone via the WP admin, but when a user subscribes to the site (using BuddyBoss form, no user is subscribed to Mailchimp. It seems like it should work since once the user subscribes to the site, they are added as a subscriber in WP just as if I had added them directly. Any Advice?
Thanks so much.