1. Go to this GitHub Repo and add the Mailchimp.php file to your project
Mailchimp.php is found in the src folder. Unless you need batch operations or webhooks, this is the only file you’ll need.
2. Include this file
This whole setup really should go into its own plugin. If that’s the case, in your main PHP file include the MailChimp.php file to use it:
include( plugin_dir_path( __FILE__ ) . 'Mailchimp.php');
If for some reason you want to referece it in your functions.php you could use:
include(dirname(__FILE__) . '/MailChimp.php');
Now the main file is included and you can start using the super simple commands.
3. Create an instance of the MailChimp object
First, I would suggest storing the MailChimp API key in the wp_config.php file. You can place in there as such:
define('MC_KEY', 'your mailchimp api key goes here');
Then you can reference it anywhere with MC_KEY.
So let’s create an instance and print out our MailChimp lists to see that everything is working:
$MailChimp = new \DrewM\MailChimp\MailChimp(MC_KEY);
$lists = $MailChimp->get('lists?count=100');
print_r($lists);
Note that MailChimp only pulls like 9 lists at a time, this I put the count at 100 to get all.
If all goes well, you should see your MailChimp lists info printed on the screen and will be ready to set up MailChimp API in WordPress
4. Examples
Example 1: Getting a list ID (in this case, the first on the list):
$list_id = $lists['lists'][0]['id'];
Example 2: Checking if the user exists. If not, then subscribing them to the list. If they do, then failing silently (or doing whatever you want, probably a PUT):
// User this array to pass values like first name, last name, city, etc.
$merge_vars = array();
if (isset($_POST['field_1'])) {
$merge_vars['FNAME'] = 'Joe';
}
// Checking if user exists in list
$subscriberHash = $MailChimp->subscriberHash($mc_email);
$duplicateCheck = $MailChimp->get('lists/' . $list_id . '/members/' . $subscriberHash);
// If returned 404 then user does not exist and we can post the data. Else do not post.
if ($duplicateCheck['status'] === 404) {
$result = $MailChimp->post("lists/$list_id/members", [
'email_address' => 'joe@example.com',
'status' => 'subscribed',
'merge_fields' => $merge_vars,
]);
// For testing. Print results on success and error on fail.
if ($MailChimp->success()) {
print_r($result);
} else {
echo $MailChimp->getLastError();
}
} else {
// To test only
die('Person already subscribed');
}
How to pass data from BuddyPress registration form to MailChimp on Submit
In my project, I had to pass data from the BuddyPress registration form to Mailchimp.
To do this, you can use the hook that fires right after you submit the form:
add_action( 'bp_core_signup_user', 'your_function' );
Conclusion
And that is how to set up the MailChimp API in WordPress using DrewM’s API wrapper.
The rest of the capabilities and functions you can read up on from the GitHub repository.