MailChimp is one bad-ass email marketing and email list management tool.
Contact form 7 is also one of the most popular free contact forms for WordPress. Wouldn’t it be nice if they worked together?
With a bit of PHP magic, here’s how to create a MailChimp opt-in field for Contact Form 7 which automatically adds an email address to a MailChimp list.
Create your MailChimp List
Login to your MailChimp account and either select an existing list or create a new one.
Get Your MailChimp API Key
To get your MailChimp API key, from the main menu select Account > API Keys & Authorized Apps.
Store this key somewhere temporary such as Notepad. You’ll need it later.
Create Your Contact Form
Create whatever type of contact form you like but add the following field somewhere on your form.
[gist id=8142647 file=code-snippet-1.php]
This adds a text field with ID [codelet]your-name[/codelet] for the
Note: there are spaces in between the square brackets in the code snippet. You’ll have to remove those if
Here’s our General Contact form with
Download API File
You will need to download the MailChimp API code from here and upload it to your themes folder.
I suggest you create a folder called includes inside your theme folder and place the [codelet]MCAPI.class.php[/codelet] file in there.
Note: the file has been zipped up for convenience. You’ll have to unzip it first on your local computer.
Add Code to functions.php
Once you have uploaded the MCAPI.class.php file to your themes’ includes folder open your functions.php file and add the following code.
[gist id=8142647 file=code-snippet-2.php]
The code has comments throughout to guide you so I’ll just
Lines 7-15 check to see if the checkbox [codelet]mailchimp-optin[/codelet] has been checked.
If it has, it then grabs the data entered into the name field [codelet]your-name[/codelet] and splits it apart using a space to get the first and last name (ignoring any middle names).
Lines 17-21 adds the information to the variables needed by the MailChimp API, including the email address from the [codelet]your-email[/codelet] form field.
Line 23 loads in the MailChimp API that we uploaded earlier.
Lines 25-26 Replace [codelet]YOURAPIKEY[/codelet] with your MailChimp API Key which can be found at http://admin.mailchimp.com/account/api/
You have to be logged in first!
Lines 28-30 Replace [codelet]YOURLISTID[/codelet] with your MailChimp List ID – the one you want the name to be added to.
You can find your lists at http://admin.mailchimp.com/lists/
View the list you want to add the information onto, then click on Settings and the Unique List ID is at the bottom of that page.
Test Your Form
The last thing to do is to test your form.
Enter some information then switch over to your MailChimp list, refresh and you’ll see a new subscriber.
Note: it may take a minute or two for the list to refresh.
Congratulations! You’re now on your way to building an email marketing list.