Masahiko Sunami

Integrating Contact Form 7 to MailChimp – the Better Way

FreddieRecently, I had to figure out how to integrate excellent Contact Form 7 plugin for WordPress to a MailChimp list, so when someone uses the contact form on the site, his/her name and email address are added to MailChimp list. I thought it won’t be that hard to find the answer, since MailChimp offers an array of API calls, but to the contrary, my search didn’t really get me what I was looking for, so now that I figured it out, I thought I’d put it out there for others to use.

My initial search yielded this post, suggesting that I modify the Contact Form 7 code itself, which is what I definitely didn’t want to do. I also found this post which talks about using wpcf7_mail_sent action hook to send form data to a custom database. So with some reference to the MailChimp listSubscribe API, I came up with a solution to use contact form action hook to subscribe contact to a MailChimp list.

First, you need:

  • MailChimp Account, and a list to add the contact info to.
  • MailChimp API key ( Account -> API Keys & Authorized Apps )
  • Unique ID for the list ( List Name -> Settings -> Settings and Unique ID )
  • MCAPI.class.php file, which is available here. ( UPDATED 2012.10.12: Scroll down to section “PHP” and download the MCAPI mini v1.3.1 file. Download the MCAPI v1.3.1 (current) if you want to reference the help text in there. )
  • A contact form using Contact Form 7. I modified it to collect First Name and Last Name separately so it matches the MailChimp list.
  • Groups in the MailChimp list that matches the name of the contact forms (if you want to separate your contact into different subgroups).

Then, put the MCAPI.class.php file in your theme folder, and add the following code to your function.php file, replacing API KEY and Unique ID with your own:

function wpcf7_send_to_mailchimp($cfdata) {

$formtitle = $cfdata->title;
$formdata = $cfdata->posted_data;
$send_this_email = $formdata['your-email'];
$mergeVars = array(
'FNAME'=>$formdata['your-first-name'],
'LNAME'=>$formdata['your-last-name'],
'GROUPINGS'=>array( array('name'=>'Form Used', 'groups'=>$formtitle),
));

// MCAPI.class.php needs to be in theme folder
require_once('MCAPI.class.php');

// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('--------API KEY---------');

// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "---------Unique ID---------";

// Send the form content to MailChimp List without double opt-in
$retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false);

}
add_action('wpcf7_mail_sent', 'wpcf7_send_to_mailchimp', 1);

That’s it! Now when someone uses a contact form, the contact info is added to the MailChimp list. Piece of cake, eh?


What the code does:

The add_action at the end hooks my function “wpcf7_send_to_mailchimp” to the action hook “wpcf7_mail_sent” which gets executed after the contact form mail is sent. The action hook sends the data from the contact form, from which I pull the title of the contact form, first name, last name, and email field. Then I create the merge data which I send off to the API.

This creates the merge data:

$mergeVars = array(
'FNAME'=>$formdata['your-first-name'],
'LNAME'=> $formdata['your-last-name'],
'GROUPINGS'=>array( array('name'=>'Form Used', 'groups'=>$formtitle),
));

In the contact form, I have set up fields for first name and last name, which I named “your-first-name” and “your-last-name.” These get assigned to “FNAME” and “LNAME” which are the merge tags in MailChimp list. I have also set up a group in MailChimp list called “Form Used,” and named all the subgroups using same names as the contact form list. This way, I can assign each contact into a different subgroup in the MailChimip list depending on the contact form used. Notice that it allows you to put a contact into multiple groups in “GROUPINGS” array, so that’s why it’s in an array within an array. Alternatively, you can create conditional statements using the form title so that you can select which contact form triggers the list subscription.

This is the crux of the code which sends the email and merge variable off to the API:

$retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false);

$retval is the returned value from the API call which is true (success) or false (error), but for my code I’m really not doing anything with it. Key here is that I am setting the double opt-in to false (the last argument), so a contact is added automatically to the list without confirmation, making the whole process transparent. Looking at the MCAPI.list.php, listSubscribe takes following arguments:

listSubscribe( $id, $email_address, $merge_vars=NULL, $email_type='html', $double_optin=true, $update_existing=false, $replace_interests=true, $send_welcome=false )

Here is the full explanation of the arguments:

  • $id (string) the list id to connect to.
  • $email_address (string) the email address to subscribe.
  • $merge_vars (array – optional) merges for the email (FNAME, LNAME, etc.) Note that a merge field can only hold up to 255 bytes.
  • $email_type (string – optional) email type preference for the email either: ‘html,’ ‘text,’ or ‘mobile.’ (defaults to ‘html’)
  • $double_optin (true/false – optional) flag to control whether a double opt-in confirmation message is sent. (defaults to true) Abusing this may cause your account to be suspended.
  • $update_existing (true/false – optional) flag to control whether a existing subscribers should be updated instead of throwing and error. (defaults to false)
  • $replace_interests (true/false – optional) flag to determine whether we replace the interest groups with the groups provided, or we add the provided groups to the member’s interest groups. (defaults to true)
  • $send_welcome (true/false – optional) if your double_optin is false and this is true, we will send your lists Welcome Email if this subscribe succeeds – this will *not* fire if we end up updating an existing subscriber. If double_optin is true, this has no effect. (defaults to false)

You can add more to the merge variable than I did, if you have more fields in the list, but there are some strict formatting that you need to follow for certain field types. See the comment in the MCAPI.class.php file (line 1541). There is a 250 character limit to merge variable, so I think if you are looking to capture lot of form data, you may be better off just creating the whole form within MailChimp. The drawback to that is of course you will be stuck with double opt-in which doesn’t make sense for a contact form – unless you create a form using an API…

Happy coding!


UPDATE – 2012.10.12:

Finally an update I’ve been meaning to write to give few more code examples and a debug trick that I use. Hope this will help.

1: Barebones code to check if your API is working

Test your Form with a real email address that’s not in your MailChimp list already. This only sends contact email address to MailChimip List with double opt-in. You should get two emails: one from Contact Form 7 to your contact address, and one from MailChimp to your test email address for opt-in confirmation.

function wpcf7_send_to_mailchimp($cfdata) {

$formdata = $cfdata->posted_data;
$send_this_email = $formdata['your-email'];

// MCAPI.class.php needs to be in theme folder
require_once('MCAPI.class.php');

// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('--------API KEY---------');

// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "---------Unique ID---------";

// Send the form content to MailChimp List without double opt-in
$retval = $api->listSubscribe($list_id, $send_this_email);

}
add_action('wpcf7_mail_sent', 'wpcf7_send_to_mailchimp', 1);

2: Barebones code with a debug function

I recommend using this to get your mergeVars in order. The function is same as the barebones example above, but this will print some data in “devlog.txt” file on your server root folder, so you can check your form data from Contact Form and the mergeVar that you are trying to create (you may need to create this file beforehand).

function wpcf7_send_to_mailchimp($cfdata) {

$formtitle = $cfdata->title;
$formdata = $cfdata->posted_data;
$send_this_email = $formdata['your-email'];
$mergeVars = array(
'FNAME'=>$formdata['your-first-name'],
'LNAME'=> $formdata['your-last-name'],
'GROUPINGS'=>array( array('name'=>'Form Used', 'groups'=>$formtitle),
));

// MCAPI.class.php needs to be in theme folder
require_once('MCAPI.class.php');

// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('--------API KEY---------');

// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "---------Unique ID---------";

// Send the form content to MailChimp List without double opt-in
$retval = $api->listSubscribe($list_id, $send_this_email);

//this is for debug purposes
$debug = array(
'time' => date('Y.m.d H:i:s e P'),
'formtitle' => $formtitle,
'formdata' => $formdata,
'mergevars' => $mergeVars,
'result' => $retval
);
$test_file = fopen('devlog.txt', 'a');
$test_result = fwrite($test_file, print_r($debug, TRUE));

}
add_action('wpcf7_mail_sent', 'wpcf7_send_to_mailchimp', 1);

In the devlog.txt file, you should see

  • date and time when it was processed
  • form title
  • form data (array)
  • mergeVars (array)
  • returned value from MailChimp API (’1′ for success, ’0′ for fail)

Here is an example of devlog.txt. I set up a test form titled “MailChimp Test” with first name, last name, email, subject, message, as well as a checkbox for opt-in (named “mailchimp-opt-in”). For this example the checkbox was checked.

Array
(
    [time] => 2012.10.12 21:22:25 UTC +00:00
    [formtitle] => MailChimp Test
    [formdata] => Array
        (
            [_wpcf7] => 214
            [_wpcf7_version] => 3.3
            [_wpcf7_unit_tag] => wpcf7-f214-p215-o1
            [_wpnonce] => d37d3e08ac
            [your-first-name] => Test
            [your-last-name] => User
            [your-email] => -----my test email---
            [your-subject] => Test 
            [your-message] => This is a test message.
            [mailchimp-opt-in] => Array
                (
                    [0] => Please check if you would like to sign up for the newsletter.
                )

            [_wpcf7_is_ajax_call] => 1
        )

    [mergevars] => Array
        (
            [FNAME] => Test
            [LNAME] => User
            [GROUPINGS] => Array
                (
                    [0] => Array
                        (
                            [name] => Form Used
                            [groups] => MailChimp Test
                        )

                )

        )

    [result] => 1
)

3: Simple Integration with just First Name and Last Name

Here is the simple example with just the first name and last name. This should automatically add contact to your list.

function wpcf7_send_to_mailchimp($cfdata) {

$formtitle = $cfdata->title;
$formdata = $cfdata->posted_data;
$send_this_email = $formdata['your-email'];
$mergeVars = array(
'FNAME'=>$formdata['your-first-name'],
'LNAME'=> $formdata['your-last-name']
);

// MCAPI.class.php needs to be in theme folder
require_once('MCAPI.class.php');

// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('--------API KEY---------');

// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "---------Unique ID---------";

// Send the form content to MailChimp List without double opt-in
$retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false);

}
add_action('wpcf7_mail_sent', 'wpcf7_send_to_mailchimp', 1);

4: Simple Integration with Opt-In checkbox

For this to work, you need a checkbox in your contact form with single option. I set up a contact form with a checkbox named “mailchimp-opt-in”. Since this value will be empty if unchecked, I just do the simple if statement.

function wpcf7_send_to_mailchimp($cfdata) {

$formtitle = $cfdata->title;
$formdata = $cfdata->posted_data;

if( $formdata['mailchimp-opt-in'] ) {

$send_this_email = $formdata['your-email'];
$mergeVars = array(
'FNAME'=>$formdata['your-first-name'],
'LNAME'=>$formdata['your-last-name']
);

// MCAPI.class.php needs to be in theme folder
require_once('MCAPI.class.php');

// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('--------API KEY---------');

// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "---------Unique ID---------";

// Send the form content to MailChimp List without double opt-in
$retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false);

} // end if

}
add_action('wpcf7_mail_sent', 'wpcf7_send_to_mailchimp', 1);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  1. Jasmine
    August 4, 2014 at 2:06 pm

    I used used the simple Integration with Opt-In checkbox sample you provided and I have to say it works great.

    My question to you is I have a second form with a different email list I want to use so how can I integrate a second opt-in check box that uses a different email list?

    Thank you.

  2. Mizzinc
    July 19, 2014 at 6:09 pm

    CF7 V3.9

    posted_data is not included in $cfdata. So how do we get the email address?

    • Mizzinc
      July 19, 2014 at 6:38 pm

      Never mind, here is the answer.

      $submission = WPCF7_Submission::get_instance();
      $formdata = $submission->get_posted_data();

  3. Steve Marks (BIOSTALL)
    February 26, 2014 at 9:40 am

    Wow! This post has just saved my a***! Was trying all kinds of plugins to no avail due to my bespoke scenario. Then came across this post and it worked right away!

    Cheers :)

  4. Danny van Kooten
    November 15, 2013 at 5:54 am

    Hi Masahiko,

    I am the author of a plugin called MailChimp for WP and came across this article by Googling around a little. Using the `wpcf7_mail_sent` is a big improvement over editing the core CF7 plugin files already.

    Just wanted to give you a quick heads up that the same could be accomplished with my plugin. It provides you with a CF7 template shortcode which will render a checkbox asking the visitor to subscribe. No custom code necessary.

    Also, the MCAPI class uses cURL which is not installed on some servers (shame on them..). The plugin uses the WordPress HTTP API which utilizes fallback HTTP methods, it will practically work on ANY server.

    Hope it can be of use to you or your clients.

    Thanks,

    Danny

    • Duecaz
      March 31, 2014 at 5:04 am

      Really easy!
      Really Works!

    • Alexandre
      June 18, 2014 at 8:28 am

      Hi Danny, how i use this shortcode?
      Thanks man!

  5. Claire
    November 1, 2013 at 5:06 am

    I have a group called WORK- how do I adjust this in the .php file?

  6. Chris
    October 23, 2013 at 4:44 pm

    I had a bunch of trouble getting this to work, but succeeded in the end.

    If you proceed carefully with the instructions but submit the form and get the endless spinning arrow, then

    (1) as @Jeff suggested, check the API log at MailChimp. See if you are successfully making calls. If not, debug.

    (2) If success with API calls, then start disabling plugins. I found a plugin conflict

    Hope this helps.

  7. Mike
    October 18, 2013 at 5:19 am

    Thanks so much for this!
    I was going crazy trying to find a way to get my form data into mailchimp. Using this method I was able to pull in all of my fields so that I can segment my list easier. And thanks to all of these great comments I was able to figure out why it wasn’t working at first!

  8. Peter
    October 13, 2013 at 12:16 am

    Hi,

    When an auto-responder is setup I do not see the subscribers who were added using the API. When viewing who should receive the next auto-responder no one added with the API is listed. When I add an email using MC’s general form it’s listed fine. Is this a problem or restriction with the API, should any extra data be sent from the form?

    Thanks

  9. Nelson
    September 30, 2013 at 1:21 pm

    I’m having a hard time trying to getting this to work. I don’t know much about coding, but I follow all the steps and use this code:

    title;
    $formdata = $cfdata->posted_data;

    if( $formdata['mailchimp-opt-in'] ) {

    $send_this_email = $formdata['your-email'];
    $mergeVars = array(
    ‘FNAME’=>$formdata['your-first-name'],
    ‘LNAME’=>$formdata['your-last-name']
    );

    // MCAPI.class.php needs to be in theme folder
    require_once(‘MCAPI.class.php’);

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI(‘——–API KEY———’);

    // grab your List’s Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the “settings” link for the list – the Unique Id is at the bottom of that page.
    $list_id = “———Unique ID———”;

    // Send the form content to MailChimp List without double opt-in
    $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, ‘html’, false);

    } // end if

    }
    add_action(‘wpcf7_mail_sent’, ‘wpcf7_send_to_mailchimp’, 1);”>

    And I’m having a Fatal Error message with the last line of the code (add_action(‘wpcf7_mail_sent’, ‘wpcf7_send_to_mailchimp’, 1);)

    Really don’t know what to do, I’ll REALLY appreciate your help guys…

  10. Jeff
    September 16, 2013 at 5:46 am

    It’s still working fine with the new MCAPI.class.php. If you have no email registred in your list, check your MailChimp API “last calls” section. It gives you information why it failed.

  11. Luke
    September 12, 2013 at 3:51 pm

    all about taking out the GROUPINGS — if you don’t assign groupings that is — and it works like a charm :) THANKS A TON MAS!

  12. James
    August 23, 2013 at 12:45 am

    Pulling my hair out trying to get this to work!

    The contact form is coming through to my email fine, but no emails are being added to my mail chimp list.

    I’m starting with the basics – barebones code with debug function. So far I’ve:

    - Placed the MCAPI.class.php in my child theme folder
    - Added the code provided above in my child themes function.php
    - Ensured my form fields match those in the functions.php code
    - Inserted my unique list ID & API key.
    - Deleted the code for ‘Groupings’, ensuring I keep the closing );

    I’ve set up the ‘devlog.txt’ file but am just getting a [result] => after submitting the contact form.

    I’ve tried this with the most recent version of Contact Form 7 (3.5.2), but also attempted it with an older version (3.3.2). But still no luck.

    Anyone help or suggestions would be amazing! Is this still working for everyone else?

    • Andy Donnan
      September 5, 2013 at 7:20 am

      I just realized mine quit working around june or july. Can’t remember if it was a theme switch that caused it, or a plugin update.

  13. Ricardo
    August 14, 2013 at 4:00 am

    Gracias por el post y las explicaciones, aunque me ha costado unas horitas adaptarlo, al final funciona perfectamente.
    Blogs como este nos hacen la vida más fácil. Sigue así

    • Profesor Yeow
      October 12, 2013 at 11:02 pm

      Ricardo! Puedes ayudarme a configurarlo? no logro hacerlo andar… Gracias!

  14. Talji
    August 7, 2013 at 1:30 pm

    Very very useful! I can verify that this still works currently and has been a big help for the website I’ve been working on.

  15. Anthony
    July 6, 2013 at 5:41 am

    Thanks for providing such a helpful tool for us WP and MailChimp users.
    I’m unable to pass any new subscribers to MailChimp, despite many hours of trying. I wonder if the new MailChimp API (MCAPI v1.3.1), WordPress 3.5.2 or Contact Form 7 3.4.2 could be sabotaging my attempts?

    Specifically I’m trying to add a tick box for people who complete a “Contact Form” to opt-in to a MailChimp List Group.

    Everything seems perfect, but the debugger returns no value against MC activity and to submit animation never completes. The emails from Contact Form 7 go through though.

    Any help would be greatly appreciated.

  16. Anthony
    July 1, 2013 at 7:21 am

    I was excited to find these instruction tonight!

    I spent 4 hours trying to implement this in WP 3.5.2 with MCAPI v1.3.2 (current) (1.3.1 unavailable). No luck.

    Wanted Groupings & checkbox for Opt-in. Added debug successfully.
    Receive emails from Contact Form 7, but checking mailchimp-opt-in checkbox results in endless spinning and no subscriptions.

    Wondered if my checkbox or form title were named in the wrong place… tried every combination. Simplified names of Groups and Subs in Mailchimp too. Also tried Mailchimp ID as displayed in URL as well as List ID, just in case List ID wasn’t really what you meant. I was desperate.

    Have been editing functions.php, despite instructions stating to edit function.php.

    Has something changed which makes this no longer work?
    *Pulling my hair out* :(

  17. Rob W
    June 28, 2013 at 5:36 pm

    Guys,

    If you’re not getting a response or an empty result, check your MailChimp API “last calls” section – it will tell you the error. Chances are, you’re using groupings when they’re not configured in mailchimp.

    Otherwise this little mod works flawless!

    Thanks,
    RW

  18. chema
    June 25, 2013 at 7:37 am

    where is the unique list id on the new mailchimp interface?

  19. Radi
    June 17, 2013 at 10:42 am

    Hi, Thanks for the great work, this is working for me on one of my accounts, but it is not working on the other. I was wondering would that work if I have more than one instance of contact forms on my website? I have a website in English and French, and have two contact forms already for people who want to leave me a message, now I added up one more contact form that I wanted to act as a submission to my mailchimp newsletter, I did everything correct, but all I am getting is the confirmation message to my mailbox, no emails is added to the list, Thank you in advance for any help!

  20. Joris
    April 12, 2013 at 7:56 am

    Hello,

    It’s working perfect except —> Checkboxes.

    I want to put multiple checkboxes on my form (requesting whitepapers) however the data won’t go into the mailchimp list… can you please explain how to get this done?

    Thank you in advance!

    • Steph
      May 26, 2013 at 4:48 pm

      I’m also having this problem, if anyone knows how to get checkbox fields working that would be great!

      • Joris
        June 22, 2013 at 10:37 am

        you just have to add [0] behind the code so it becomes:

        ‘LNAME’=>$formdata['your-last-name'][0],

        • Claire
          November 1, 2013 at 4:19 am

          This works, but it only saves one of the options – I want it to be able to save multiple options. I have a list of types of work & they can choose as many as they like.

          I have
          ‘WORK’=>$formdata['WORK'][0],

          In my code…

          Great help btw, would love to get this final bit working..

  21. Paul Hamon
    March 31, 2013 at 8:00 pm

    Worked like a charm, thank you :)

    If you’re NOT using groups, then just delete the line below… but make sure you match up the closing brackets… two opens and two closes!

    ##–

    ‘GROUPINGS’=>array( array(‘name’=>’Form Used’, ‘groups’=>$formtitle),
    ));

    ##–

    As “);” belongs to the “$mergeVars = array(” and nothing to do with GROUPINGS!

  22. Bailey
    March 25, 2013 at 10:49 pm

    Thanks! This is great.

  23. Chris Dunst
    March 18, 2013 at 2:54 pm

    Hi,

    Firstly, thanks for this code and the guidance. I’m having problems however, I hope you can point me in the right direction?

    I have uploaded the MCAPI class to the theme directory, added your code to my functions file, and changed the form input names, api key and list id, so all should be well.

    My form submits fine, but the email doesn’t get added to my Mailchimp list. I tried your debugging version, and all of the data in the txt file seems correct, except for the result, which is empty – there is no 0 or 1.

    I also tried removing the groupings from the merge vars, but no cigar.

    Any ideas? Thanks in advance

  24. Jeff
    March 12, 2013 at 5:44 am

    Last night you save my life ! Working like a charm.

  25. Mabel
    March 12, 2013 at 4:25 am

    Hi Mas,

    Thanks very much for your post, but I need some help.

    In your explanation you write: “Then, put the MCAPI.class.php file in your theme folder, and add the following code to your function.php file, replacing API KEY and Unique ID with your own:”

    I don’t understand where exactly (in which theme folder) I have to put the MCAPI.class.php file???
    Also, where exactly do I have to add the code????

    Sorry, just starting to learn all this now…

    Thanks,
    Mabel

  26. Kun
    February 26, 2013 at 12:49 pm

    I must say, Mas. This is a great post!
    Maybe the codes are a lil too small to read through, but the technique is impecable!

    Kudos!

  27. robb luther
    February 20, 2013 at 8:31 am

    This is a great tutorial, but what if I want to update data based on other forms. For example, I want one form as my opt in… but a second form may have the name fields…

    I tried doing an update, but to no avail…

    • robb luther
      February 20, 2013 at 11:01 am

      This is how i am coding my listSubscribe:
      // Send the form content to MailChimp List without double opt-in
      $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars,$update_existing=true, ‘html’, false);

    • mas
      February 21, 2013 at 5:11 am

      Hi Robb,

      listSubscribe argument are bunch of texts and values (true/false) and they need to be placed in a specific order. So if you want to set the $update_existing value to true, then you need to put that as the sixth argument:

      listSubscribe( $id, $email_address, $merge_vars, 'html', FALSE, TRUE)

      Fifth argument sets the double opt-in option, so this example will set the new contact without double opt-in, and will update the contact information with the merge variables that you specify (whatever you assing to $merge_vars in your code).

      Hope that helps.

      • Robb Luther
        February 21, 2013 at 5:16 am

        Yes, I finally figured out the sequence yesterday! You post was a huge help! Thank you very much.

  28. JT
    February 20, 2013 at 1:18 am

    This was a great help. Took a little while for me to get my head around it, but works perfectly now.

    Thank you. ;)

  29. Jonny V
    February 7, 2013 at 8:53 am

    Copy, paste, job done.

    Thank you very much for this – it’s saved me several hours of work.

  30. David
    January 26, 2013 at 11:20 pm

    Installed, followed instructions (natch) form works and sends email to recipient and myself as it did before, but nothing is being added in MailChimp… Tracked down that the calls are coming in but I’m getting a “(270) List_InvalidInterestGroup” error response (with, of course, no indication how to resolve said error.

    I have no Groups created on MailChimp

    since reportedly all I have to do is follow the instructions above, cut and paste and this works perfect as is, that’s all I did.

    Since I have no Groups created on MailChimp, I removed the line of code re: Groupings and immediately my entire wordpress installation crashed.

    I fiddled with the last line based on feedback below, still to no avail…

    So… HOW DO I RESOLVE THIS 270 ERROR AND GET THIS TO WORK? IDEAS?

    What I have in my functions.php:


    function wpcf7_send_to_mailchimp($cfdata) {

    $formtitle = $cfdata->title;
    $formdata = $cfdata->posted_data;
    $send_this_email = $formdata['your-email'];
    $mergeVars = array(
    'FNAME'=>$formdata['first-name'],
    'LNAME'=>$formdata['last-name'],
    'EVENTTYPE'=>$formdata['your-event'],
    'EVENTDATE'=>$formdata['your-event-date'],
    'MESSAGE'=>$formdata['your-message'],
    'PHONE'=>$formdata['your-phone'],
    'EMAIL'=>$formdata['your-email'],
    'GROUPINGS'=>array( array('name'=>'Form Used', 'groups'=>$formtitle),
    ));

    // MCAPI.class.php needs to be in theme folder
    require_once('MCAPI.class.php');

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI('**********');

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page.
    $list_id = "**********";

    // Send the form content to MailChimp List without double opt-in
    $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false);

    }
    add_action('wpcf7_before_send_mail', 'wpcf7_send_to_mailchimp', 1);

    • mas
      January 27, 2013 at 6:10 am

      Hi David,
      Thanks for your comment. If you are not using any groups, you should delete the line for ‘GROUPINGS’. If you are in doubt if it’s working at all, I suggest following some troubleshooting tips I wrote on the post.
      mas

    • David
      January 27, 2013 at 7:16 am

      Since I have no Groups created on MailChimp, I removed the line of code re: Groupings and immediately my entire wordpress installation crashed.

      • mas
        January 27, 2013 at 9:38 am

        Right. That’s why you should try the simpler examples first. You probably have some syntax error in your code.

  31. John
    January 14, 2013 at 9:48 am

    Anyone know how to pass the Phone Number Field? Tried
    ‘PHONE’=> $formdata['your-phone'] but it didn’t work.

    • mas
      January 14, 2013 at 10:03 am

      I believe you want to you use ‘phone’ rather than uppercase ‘PHONE’. Also, you have to make sure that the phone number is in a specific form. Here’s what it says in the documentation: If your account has the US Phone numbers option set, this must be in the form of NPA-NXX-LINE (404-555-1212). If not, we assume an International number and will simply set the field with what ever number is passed in.
      Good luck!

      • John
        January 15, 2013 at 5:57 am

        Thanks Mas for the help. Tried ‘phone’ that but it didn’t work even in that format. Setting on form itself I hope is correct as.
        [text* phone 32x15 watermark "Phone*"]
        I tried ‘your-phone’ as well for the text name. No luck. As far as I could tell from Contact Form 7 documentation, a phone is just a text field.

        • mas
          January 18, 2013 at 12:39 am

          Just trying to be clear:
          [text* phone 32x15 watermark "Phone*"] will display a watermarked text input field with a name “phone” and initial value set at “Phone*”. Value 32×15 is an option for textarea and not for input field. If you want to set a field size and max field size then syntax is something like 4/10.
          For an input field in CF7 with a name “phone”, you want to add this in the $mergeVars array:
          ‘phone’=>$formdata['phone']
          If you have an CF7 field with a name “your-phone”, then it will be this:
          ‘phone’=>$formdata['your-phone']
          I know from experience that adding extra mergeVars is tricky. Hope it will work for you…

  32. John
    January 12, 2013 at 9:18 am

    Thanks for sharing this solution. Worked perfectly. Easiest solution I’ve found.

  33. Rashed
    December 26, 2012 at 11:57 pm

    Great !!! Worked like a charm :)

  34. Chris
    December 5, 2012 at 6:44 pm

    Excellent idea! Thanks for sharing… I have a question however.

    I get no result no matter what I do.

    I am using the form without checkbox opt in and the functions code for automatic opt in.

    I have played with this for hours and not come up with a solution to it.

    What does it mean if you get a null result as opposed to 0 or 1?

    On the mailchimp side the API is recording triggers but all failures?

    Here is my form / code / result being used currently… all responses appreciated.

    FORM :

    Your First Name (required)
    [text* your-first-name]

    Your Last Name (required)
    [text* your-last-name]

    Your Email (required)
    [email* your-email]

    Your Question Summary
    [text your-subject]

    Your Question
    [textarea your-question]

    [submit "Send Your Question"]

    CODE:

    function wpcf7_send_to_mailchimp($cfdata) {

    $formtitle = $cfdata->title;
    $formdata = $cfdata->posted_data;
    $send_this_email = $formdata['your-email'];
    $mergeVars = array(
    ‘FNAME’=>$formdata['your-first-name'],
    ‘LNAME’=>$formdata['your-last-name'],
    ‘GROUPINGS’=>array( array(‘name’=>’Form Used’, ‘groups’=>$formtitle),
    ));

    // MCAPI.class.php needs to be in theme folder
    require_once(‘MCAPI.class.php’);

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI(‘XXXXXX’);

    // grab your List’s Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the “settings” link for the list – the Unique Id is at the bottom of that page.
    $list_id = “XXXXX”;

    // Send the form content to MailChimp List without double opt-in
    $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, ‘html’, false);

    //this is for debug purposes
    $debug = array(
    ‘time’ => date(‘Y.m.d H:i:s e P’),
    ‘formtitle’ => $formtitle,
    ‘formdata’ => $formdata,
    ‘mergevars’ => $mergeVars,
    ‘result’ => $retval
    );
    $test_file = fopen(‘devlog.txt’, ‘a’);
    $test_result = fwrite($test_file, print_r($debug, TRUE));

    }
    add_action(‘wpcf7_mail_sent’, ‘wpcf7_send_to_mailchimp’, 1);

    RESULT:

    Array
    (
    [time] => 2012.12.06 02:20:59 UTC +00:00
    [formtitle] => Questions
    [formdata] => Array
    (
    [_wpcf7] => 13
    [_wpcf7_version] => 3.3.1
    [_wpcf7_unit_tag] => wpcf7-f13-p1-o1
    [_wpnonce] => 76b93164fe
    [your-first-name] => A
    [your-last-name] => Person
    [your-email] => testemailobscured
    [your-subject] => subject text
    [your-question] => help
    [_wpcf7_is_ajax_call] => 1
    )

    [mergevars] => Array
    (
    [FNAME] => A
    [LNAME] => Person
    [GROUPINGS] => Array
    (
    [0] => Array
    (
    [name] => Form Used
    [groups] => Questions
    )

    )

    )

    [result] =>
    )

    Thanks for reading…
    Chris

    • Rock
      April 4, 2013 at 12:29 pm

      I have the same problem the result is null.
      [result] =>

      I used all simple codes, and nothing work, tested in 2 different sites.

  35. Manzurul Haque
    November 29, 2012 at 4:41 am

    This thing is not working. Its just showing the spinning when I submit form but it does sent email but doesnt give any confirmation.

    • mas
      November 30, 2012 at 2:49 pm

      Hi Manzurul,
      The wheel will spin forever if you have an error in your code, since it takes place after CF7 sends an email, and before it displays a confirmation text on screen. Does it actually add contact to your MailChimp list? Try the simpler code examples here so you can figure out what’s wrong with your code.

  36. Robert
    November 28, 2012 at 10:54 pm

    Hi Mas,

    First off, thank you for this great solution!

    I seem to be having some trouble with a second form that I just created. My first form works fine and adds form data to my MailChimp list. On my second form, I still receive the form submission confirmation e-mails, but now it does not add the form data to the MailChimp list.

    The second form is a duplicate of the first (working) form. The only differences between the 2 forms are the ID and the text of the e-mail response people receive when they submit the form.

    Please let me know your thoughts when you have a spare moment. Thanks again!

    Robert

    • mas
      November 30, 2012 at 2:40 pm

      Hi Robert,
      Thanks for your comment. Check your form title and check your code and make sure that they match. If you are putting contacts to different groups in MailChimp, then make sure that your group names are correct. When in doubt, try stripping down your code to troubleshoot. Sorry- I haven’t found any easy way to troubleshoot the code…

      • Robert
        December 4, 2012 at 1:05 pm

        You’re the man! I totally forgot to create a new sub-group for this second form in MailChimp. Once I did that, my test submission showed up in my subscriber list.

        Case closed, thanks so much!

        Robert

  37. Dre
    November 20, 2012 at 5:12 am

    Thanks for this code! I’m having a slight issue getting it to display a success (or even error) notification. The form itself is working; the email is being sent and the data is going successfully being passed to the mailing list. However on submit I just get the spinning icon, with no notifications.

    // MAILCHIMP INTEGRATION ON COMPETITION FORM

    function wpcf7_send_to_mailchimp($cfdata) {

    $formtitle = $cfdata->title;
    $formdata = $cfdata->posted_data;

    if( $formtitle == ‘Contest Form’ ) {

    $send_this_email = $formdata['your-email'];
    $mergeVars = array(
    ‘FNAME’=>$formdata['fname'],
    ‘LNAME’=>$formdata['lname'],
    ‘EMAIL’=>$formdata['your-email'],
    ‘COMP’=>$formdata['org'],
    ‘OPTIN’=>$formdata['mailchimp-opt-in'][0],
    ‘LCONT’=>date(‘d/m/Y’),
    ‘ANSWER’=>$formdata['answer']
    );

    // MCAPI.class.php needs to be in theme folder
    require_once(‘MCAPI.class.php’);

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI(‘*******’);

    // grab your List’s Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the “settings” link for the list – the Unique Id is at the bottom of that page.
    $list_id = “*****”;

    // Send the form content to MailChimp List without double opt-in
    $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, ‘html’, false);

    //this is for debug purposes
    $debug = array(
    ‘time’ => date(‘Y.m.d H:i:s e P’),
    ‘formtitle’ => $formtitle,
    ‘formdata’ => $formdata,
    ‘mergevars’ => $mergeVars,
    ‘result’ => $retval
    );
    $test_file = fopen(‘devlog.txt’, ‘a’);
    $test_result = fwrite($test_file, print_r($debug, TRUE));

    // Return message
    if ($retval==1) {
    echo “Answer submitted”;
    } else {
    echo “”;
    if ($api->errorCode == 214) {
    echo “This email address has already entered this competition”;
    } else {
    echo “Sorry, there has been an error. “;
    }
    echo “”;
    }

    } // end if

    }
    add_action(‘wpcf7_mail_sent’, ‘wpcf7_send_to_mailchimp’, 1);

    Any idea where I’m going wrong? I’m not adverse to redirecting to another page if AJAX is out of the question.

    Thanks!

    • mas
      November 21, 2012 at 3:32 pm

      Hi Dre,
      The function takes place after page is loaded, so ‘echo’ won’t do anything. I believe CF7 uses AJAX to print message to the hidden div underneath the form, so may be there is a way to hijack the process to show your custom messages, but sorry I can’t really help you there…
      cheers,
      Mas

      • Dre
        November 22, 2012 at 2:15 am

        Hi Mas,
        Thanks for the reply. There’s a second form on the site which isn’t using the Mailchimp integration, and the AJAX there does work, so I’m guessing it’s something to do with the integration, rather than a general problem with the CF7 itself. I’ll keep digging!

        • mas
          November 30, 2012 at 2:46 pm

          Hi Dre,
          You will see the wheel spin forever if you have an error in your code. The code takes place after email is sent from the contact form, before it displays a success message on screen, so if something goes wrong, the process will just die, and it won’t get to displaying the success message.
          Please do share if you ever figure it out!

          • Kristy
            January 14, 2013 at 7:24 am

            I was having the same problem – everything working flawlessly but the wheel kept spinning. I changed the action hook in the last line to:
            add_action('wpcf7_before_send_mail', 'wpcf7_send_to_mailchimp', 1);

            Now it works perfectly! Sends the email and adds the subscriber.

          • Ricardo
            June 21, 2013 at 8:47 pm

            That was the aswer for me too Kristy. But in my case the ajax was working and the subscriber was added, but I didn’t receive the CF7 email.

  38. Jill
    November 1, 2012 at 6:08 am

    I’m trying to allow the person who fills out the form to select their interests and then be added to a group (or groups) in Mailchimp based on their selection…

    Right now I have:

    'GROUPINGS'=>array(
    array('name'=>'Interest', 'groups'=>$formdata['interest']),
    )

    where $formdata['interest'] references a checkbox on the contact form with three different options – unfortunately this isn’t working, however… if I replace $formdata['interest'] with ‘Interest1,Interest2,Intrerest3′ it does work and puts the user into those three groups… problem being that some people may only be interested in 1 or 2, instead of all 3…

    can you help with this at all?

    many thanks for your hard work!

    • mas
      November 3, 2012 at 12:27 pm

      HI Jill,
      If you use the debug trick you should see the result from your check boxes, but in general, check box will yield a data that is in array form, so

      $formdata['interest']

      in your case will be an array with all the checked entries. You probably want to try to make that into a text string, something like this which will use commas as a separator:

      implode(',', $formdata['interest'])

      cheers!

  39. Eytan
    October 31, 2012 at 8:59 pm

    Does this get called for any contact form, or is there a way to specify which form it should be called for?

    • mas
      October 31, 2012 at 9:19 pm

      You can customize the code so it only triggers on a specific form. You can modify the code for Opt-In Check box, change

      if( $formdata['mailchimp-opt-in'] ) {

      to

      if( $formtitle == 'name-of-the-form' ) {

      with your form name, then it should do the trick.

  40. Jody Bailey
    October 29, 2012 at 8:52 am

    I also am just stopping by to say thank-you for your efforts with this post/code. I’ve used your function on a couple sites now and love how malleable it is. Great work!

    I also wanted to add, that you can limit the list signup from firing if you have more than one contact form on your site. Simply use “4: Simple Integration with Opt-In checkbox” above, but instead of:

    if( $formdata['mailchimp-opt-in'] )

    use:

    if ( $cfdata->title === ‘Contact form title for which you want signup to trigger’ )

    …again, great work and thanks!

    • nicole
      February 18, 2013 at 5:09 pm

      Excuse the dumb question but where in the code do you add

      if ( $cfdata->title === ‘Contact form title for which you want signup to trigger’ )

      I have 3 forms on my site and need to capture date from them separately with an opt-in so I assume the above will enable me to do this?

  41. Eric
    October 26, 2012 at 7:14 am

    Thanks a ton!
    You made this super simple to setup and get going.

  42. Avery Z Chipka
    October 23, 2012 at 6:55 pm

    I have been trying to get this to work for awhile with no luck.

    My debug log is showing as follows, with the result field empty:

    Array
    (
    [time] => 2012.10.24 01:50:50 UTC +00:00
    [formtitle] => MailChimp Subscription
    [formdata] => Array
    (
    [_wpcf7] => 6341
    [_wpcf7_version] => 3.3.1
    [_wpcf7_unit_tag] => wpcf7-f6341-p5345-o1
    [_wpnonce] => 64ae08def3
    [your-first-name] => Test
    [your-last-name] => Test
    [your-email] => ****
    [_wpcf7_is_ajax_call] => 1
    )

    [mergevars] => Array
    (
    [FNAME] => Test
    [LNAME] => Test
    )

    [result] =>
    )

    —-
    The below is the code from my functions.php file:
    /**
    * Add mailchimp support to contact form 7
    */

    function wpcf7_send_to_mailchimp($cfdata) {

    $formtitle = $cfdata->title;
    $formdata = $cfdata->posted_data;
    $send_this_email = $formdata['your-email'];
    $mergeVars = array(
    ‘FNAME’=>$formdata['your-first-name'],
    ‘LNAME’=> $formdata['your-last-name']
    );

    // MCAPI.class.php needs to be in theme folder
    require_once(‘MCAPI.class.php’);

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI(‘XXXXXXXXXXX’);

    // grab your List’s Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the “settings” link for the list – the Unique Id is at the bottom of that page.
    $list_id = “XXXXXXXXXX”;

    // Send the form content to MailChimp List without double opt-in
    $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, ‘html’, false);

    //this is for debug purposes
    $debug = array(
    ‘time’ => date(‘Y.m.d H:i:s e P’),
    ‘formtitle’ => $formtitle,
    ‘formdata’ => $formdata,
    ‘mergevars’ => $mergeVars,
    ‘result’ => $retval
    );
    $test_file = fopen(‘devlog.txt’, ‘a’);
    $test_result = fwrite($test_file, print_r($debug, TRUE));

    }
    add_action(‘wpcf7_mail_sent’, ‘wpcf7_send_to_mailchimp’, 1);

    —CONTENT FORM CONTACT 7 FORM—–
    Your First Name (required)
    [text* your-first-name]

    Your Last Name (required)
    [text* your-last-name]

    Your Email (required)
    [email* your-email]

    [submit "Subscribe"]

    • Avery Z Chipka
      October 23, 2012 at 6:56 pm

      Oh and clearly the XXXXX in my api is just because i overtyped it that is not what is actually in the file.

      • Avery Z Chipka
        October 23, 2012 at 7:47 pm

        Disregard previous posts. I resolved the issue. The problem was related to the length of my form name exceeding the 255 limit for the mergvars. By removing the groupings the issue was resolved and all is now well.

  43. Flash Buddy
    October 22, 2012 at 4:01 pm

    Just had to throw my thanks and 2 cents.

    Took me hours to get this working. The road block in my case was having a multi field form at MailChimp, just trying to pass the FNAME LNAME and EMAIL. I fitured that should work, don’t need all the other fields while testing. Turns out I had many required fields in my MailChimp form. When I went back and edited the form at MailChimp and removed all the required fields (except email of course), It suddenly worked!

    Thanks. I hope my mistake helps somebody else.

  44. Matthew
    October 18, 2012 at 7:53 pm

    It works perfectly!! I’ve been searching everywhere for an up-to-date way to do this. You’ve saved me a lot of time. Thank you!

  45. Zack
    October 15, 2012 at 11:12 pm

    Parse error: syntax unexpected PROBLEM!

    Great post and update, but I am having problems. I am doing the option with the opt-in checkbox. I have followed your instructions perfectly, I’m pretty sure. But with that new opt-in code, I am getting a “parse error: syntax, unexpected,” specifically on the 12th line that says this: ));

    Why is this happening? When I inserted the original code you first posted, it is fine…. But I really really need this opt-in feature! Please help!

    Zack

    • mas
      October 16, 2012 at 1:29 am

      There was an extra close parentheses on line 12. I updated it.

      • Zack
        October 17, 2012 at 11:08 pm

        Great thanks!

        I inserted it, and now I get no errors. But unfortunately, upon a contact form 7 submission, there is no communication with Mailchimp. I get no email from them for the email address that I submitted. I made sure it was a new email address that’s not already on our list. I even tried getting it to create a devlog.txt with no luck. I created the file in advance – but the .txt file remains blank, even after another form submission and that correct new code in the functions.php file.

        I don’t know why it’s not working…I am very accurate in following directions, and I am usually quick to figure things out… Maybe I missed something?

      • Zack
        October 17, 2012 at 11:23 pm

        ACTUALLY – It DOES work.

        I checked my Mailchimp list, and is IS adding the person to the list. The problem is that I don’t get any emails on either end. I don’t get the double-opt-in email for the subscribing email address (I usually do), and I don’t get an email from Mailchimp to my master email saying that somebody has subscribed. Therefore, there is no “person@gmail.com has joined your mailing list” message on the Mailchimp dashboard, either.

        Why aren’t I getting these emails? AWESOME post/coding by the way. This is just what we needed. And you said it best here – on this website. All the other ones are crap. So thanks a million in advance for helping me make this PERFECT! :)

        Zack

        • mas
          October 18, 2012 at 1:40 am

          Hi Zack,

          The code is meant to be transparent, and it specifically tells MailChimp to add the new contact without doube opt-in. If you want people to confirm subscription by having MailChimp send them an opt-in email, then you can just omit the argument for that in the API call, since double opt-in is the default:

          $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars);

          There is also an option where you can add contact to the list without double opt-in, but send the new contact a welcome email. That’s the last argument for the listSubsribe function, so you will need to write out all the other arguments as well:

          $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false, false, true, true);

          As for getting a notification from MailChimp of a new subscriber, there probably is a way, but probably little too much trouble for having a small peace of mind – because after you test and know that it works, you know that a new contact is on the list when you get an email from Contact Form 7… If you need someone else to be notified, then you can configure Contact Form 7 to send another email to different email address…

          cheers!

          • Zack
            October 19, 2012 at 1:10 am

            Oh, okay I see now!

            The welcome email one isn’t working, but that’s okay! I know that it works when I get the contact form email, like you said.

            Thank you for your help! I appreciate your time.

            Zack

  46. mas
    October 12, 2012 at 3:14 pm

    I have finally updated this post to give more examples. Hope it helps!

  47. Eli
    October 8, 2012 at 1:52 pm

    hello, if I am using a child theme with my main theme, I would like to know if this will work if I install the PHP file into my child theme directory. What do you think?

    Thanks for great instructions!!

    • mas
      October 8, 2012 at 2:45 pm

      I think it should work if you put the code in the function.php file along with MCAPI.class.php file in your child theme folder, as long as you don’t use the same name for your function that is in your parent theme function.php file.

      • Eli
        October 10, 2012 at 1:19 pm

        Set it all up in reg theme folder, not child theme. I have gone over it twice now. doesn’t add new subscribers – I keep testing it and can’t figure out why its not working. What to check on? Should I set up my contact form again – starting from scratch? I dont have a sub group in mail chimp – should I set one up? Darn, I can usually always figure these things out. Any help is appreciated!

        • mas
          October 12, 2012 at 3:10 pm

          I updated the post with simpler examples. Try that to begin with.

    • Flash Buddy
      October 22, 2012 at 4:05 pm

      Worked in the child theme directory for me.

  48. Andrea Bradley
    October 5, 2012 at 5:02 am

    Just a quick thank you for your excellent article – I was able to integrate with the API without a hitch :)

  49. Daniel
    October 5, 2012 at 1:42 am

    Hey, are there any known problems with different mailchimp API Keys? If I am using my Mailchimp Account witth the ending -us4 everything works fine, but if I’m switching to my customers API key with the ending -us5 nothing happens. I switched thousand times, always with the same result. -us4 isworking us-5 not. Any ideas?

    Thanks
    Daniel

    • mas
      October 12, 2012 at 3:13 pm

      Not really sure. My account API ends with -us6 and it seems to work just fine.

  50. Laurence
    October 3, 2012 at 7:55 am

    I’ve got this working adding subscribers to a list through a check-box in a contact form. Great! Is it possible to have them automatically added to all the groups within that list? Thanks for the help.

    • Andrea Bradley
      October 5, 2012 at 8:07 am

      There is probably an easier way but you could replace

      'GROUPINGS'=>array( array('name'=>'Form Used', 'groups'=>$formtitle),
      )

      with

      'GROUPINGS'=>array( array('name'=>'Group Title', 'groups'=>'Group Name1,Group Name2,Group Name3'),
      )

  51. Fawn
    September 9, 2012 at 9:59 pm

    Okay, wouldn’t you know it… I finally found it here: http://code.google.com/p/mcapi-php/downloads/

    Fingers crossed I can get it working…

    • Laurence
      October 3, 2012 at 7:53 am

      Thanks for the post. This is really useful.

    • mas
      October 12, 2012 at 3:09 pm

      I updated the link. You can just download the MCAPI file which is under PHP section of the page.

  52. Fawn
    September 9, 2012 at 9:56 pm

    I can’t seem find the MCAPI.class.php file anywhere! The page you link to on MailChimp says, “Woah, Nerds Only!” and I can’t find the “inc” folder you mention. I even tried Googling the name of the file, but I’m not having any luck. Help?

  53. Richard Young
    August 24, 2012 at 4:11 pm

    Hello,
    took me a while to get it to work –
    I had to put the MCAPI.class.php file in the theme /inclusive folder
    (the funtions.php that I edited is also in the /inclusive folder)

    Now it works – it’s great – I have two different forms updating to two subgroups.

    thank you

    Richard

    • mas
      August 28, 2012 at 12:23 am

      Glad you figured it out!

    • Eli
      October 10, 2012 at 2:43 pm

      So- did you add the code to the functions.php file where it existed in the main theme file? I did that and it isnt working yet for me.

  54. Alex
    August 17, 2012 at 6:29 am

    Can this tweak work for another form?

    • mas
      August 28, 2012 at 12:21 am

      Short answer is no. This is specific to Contact Form 7, but if you find an equivalent action hook for your form plugin and pull the content values, then you can modify this code to send to a MailChimp list. I don’t really have any experience with other form plugins, so I can’t give you any specifics…

  55. Elena
    August 13, 2012 at 11:53 pm

    Hi mas,

    Thanks for the great solution. I had some problems making it work at first but now it works like a charm. Very simple and straightforward :).

    Cheers!

  56. Jill
    August 7, 2012 at 3:14 am

    This is really useful, thank you. I’ve been battling with adding in an additional group a little bit and was wondering if you could help me?

    Basically, I just wanted to add in a second group to the email… the Form Title is taking care of the first group, but I also wanted to create a second group… “Add to Mailing List” with a Yes or No response. I’ve added the grouping into Mailchimp and also the checkbox to the Contact Form. This is what I’ve been trying…

    ‘GROUPINGS’=>array( array(‘name’=>’Add to Mailing List’, ‘groups’=>$formdata['mailchimp-optin']),
    )

    any idea where I’m going wrong?

    Thanks so much for any help and for providing the code in the first place, really useful!

  57. Ulrik Foldager
    July 29, 2012 at 4:07 am

    Hello!

    I tried doing this by following your exact steps, and did this:

    1) Followed your initial checkpoints at the top of your article.
    2) Copied MCAPI.class.php to the Contact Form 7/includes folder.
    3) Inserted the code snippet you provided into the functions.php file,
    4) Inserted API key and List ID into code snippet.
    5) Uploaded functions.php.

    My form looks like this:

    Your First Name (required)[text* your-first-name]
    Your Last Name (required)[text* your-last-name]
    Your Email (required)[email* your-email]
    [submit "Subscribe"]

    But I still can’t get it to work. I am receiving an e-mail from the form submission, but the sender of the form does not get added to my Mailchimp list.

    Do you know what I am doing wrong? I am not very code or technical-savvy, so I’m not really sure what I am missing.

    Thank you so much!

    • mas
      July 29, 2012 at 5:58 am

      Hi Ulrik,

      The MCAPI.class.php file needs to go into your theme folder, not anywhere else.

      mas

      • Ulrik Foldager
        July 29, 2012 at 6:34 am

        Thank you, Masahiko.

        I have done that and am trying to get the Contact Form 7 to work now. It seems to work completely irrationally, unfortunately.

        I will come back with an answer when I’ve got it working.

  58. Rob Scott
    July 18, 2012 at 2:43 pm

    Just thought I’d chip in and say thanks for putting up some very useful code – has helped me to avoid a lot of work today, so thank you!

    Rob

    • mas
      July 18, 2012 at 3:58 pm

      You’re welcome!

  59. Dave
    May 4, 2012 at 10:57 am

    Don’t seems to work for me.. no error return but the new email doesn’t appear in my mail chimp list either.

  60. ib
    April 12, 2012 at 5:48 pm

    Hi, this seems like a great solution but i can’t get it to work. It seems to be making the call just fine, however if i go into ACCOUNT/API KEYS and check the LAST 24 HRS OF API CALLS, all the calls appear to be failed (red status). That makes think that the API key and unique code are ok and the script is effectively making the call but it somehow gets filtered by mailchimp or something.

    Any ideas?

    Thanks for sharing BTW

    • mas
      April 17, 2012 at 1:55 pm

      I can’t really give much technical support, but my guess is that you are trying to pass an invalid merge variable or something. Good way to make sure that your API is working is to try sending just the email – something like this:

      $retval = $api->listSubscribe($list_id, $send_this_email);

      If it’s working, you should get an opt-in email from MailChimp. I recommend keeping the merge variable fairly simple, because there really isn’t an easy way to troubleshoot the code…

      • ib
        April 19, 2012 at 9:49 pm

        I got it to work by disabling the group function. I deleted this part of code:

        ,
        'GROUPINGS'=>array( array('name'=>'Form Used', 'groups'=>$formtitle),
        )

        So i’m guessing that i didn’t fully understood how to set the group properly.

        • Jeremy
          August 9, 2012 at 11:06 pm

          Hi ib,

          thanks got it to worked by removing the groupings.

          and thank you Masahiko!

          • Michael Caputo
            August 30, 2012 at 5:24 pm

            This worked for me as well.

            Thanks for the instructions!

        • Angela
          September 19, 2012 at 3:38 am

          Whoo Hoo! Me too! I’m no php expert, so this was a struggle, but all your great input got me through it. I was having trouble with the grouping line in the code too – and didn’t realize that the closing bracket on the next line ” ) ” also needed to go. Trial and error, and now it’s working.

          Thanks guys! Beautiful work, Mas, Thanks!

  61. peter
    April 9, 2012 at 6:59 pm

    Hi Mas,
    Thankyou so much for your article.

    This inspired me to write a useful little wordpress plugin which takes care of the adding people to MailChimp from the CF7.

    For anyone interested please download it out here:
    http://wpsolutions-hq.com/plugins/contact-form-7-autoresponder-addon/

    Any feedback is welcome and encouraged:

    Will post this on wordpress.org too.

  62. Shawn
    April 6, 2012 at 11:53 am

    Without having to edit or change any files, wouldn’t this plugin do the same thing?

    http://wordpress.org/extend/plugins/contact-form-7-3rd-party-integration/

    • mas
      April 17, 2012 at 1:39 pm

      I suppose if you really don’t want to mess with your theme, you can probably implement it using that plugin. But I always try to minimize the number of plugins I use on a site, because you are adding ton of code with every plugin and it will eventually slow down your site…

  63. Chris Demetriad
    April 4, 2012 at 11:27 am

    Thank you for this article. Well written, very simple, extremely useful.

  64. brian
    March 29, 2012 at 4:44 pm

    I’m having trouble with the integration…the info is not passing to Mailchimp. Here’s what I entered:

    function wpcf7_send_to_mailchimp($cfdata) {

    $formtitle = $cfdata->title;
    $formdata = $cfdata->posted_data;
    $send_this_email = $formdata['your-email'];
    $mergeVars = array(
    ‘NAME’=>$formdata['your-name'],
    ‘GROUPINGS’=>array( array(‘name’=>’Form Used’, ‘groups’=>$formtitle),
    ));

    // MCAPI.class.php needs to be in theme folder
    require_once(‘MCAPI.class.php’);

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI(‘My API ENTERED HERE’);

    // grab your List’s Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the “settings” link for the list – the Unique Id is at the bottom of that page.
    $list_id = “UNIQUE ID ENTERED HERE”;

    // Send the form content to MailChimp List without double opt-in
    $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, ‘html’, false);

    }
    add_action(‘wpcf7_mail_sent’, ‘wpcf7_send_to_mailchimp’, 1);

  65. Phil
    March 14, 2012 at 3:14 pm

    Thanks for this, was on the silenceit one too, before i decided to move. This is a good touch, however, new subscibers are only being added to the MC list sporadically, cant seem to find out why its only working sometimes. Its causing the alert email not to be sent on to us, ie letting us know someone has signed up, standard contact form 7 behavior.

    Im assuming this is an issue my end, but cant find a solution.

    Also ive played with the function alittle,

    $mergeVars = array(
    ‘MMERGE3′=>$formdata['your-name'],

    As I have changed the fields in mailchimp to just house a full name. Is this ok, or am i rendering the mergevars pointless here and can remove?

    • mas
      March 15, 2012 at 1:07 am

      The action hook wpcf7_mail_sent gets executed after a contact mail is successfully sent, so if you are not getting the mail from the Contact Form 7, it shouldn’t be because of any code you add to the action hook. If you have issue with your code for this hook, the AJAX spinning arrow will continue to spin and you will not see the “Your mail was sent successfully” message, but you should still get the email sent to you anyway.

      You can change the field tag names from generic term like “MMERGE3″ to something more meaningful in MailChimp. If you remove the mergeVar altogether, your contact will still be added to your list, just that only your email will be added to the list.

      • Phil
        March 15, 2012 at 1:32 pm

        Thnks for the info Mas. I think it was cache issue, seems to be working flawlessly now.

        • David
          April 27, 2012 at 6:27 pm

          Hi Phil,

          I’m having the same error you are where the email address isn’t being parsed to mailchimp. When you can it was a ‘cache issue’, how did you solve it?

          Thanks.

          Dave

  66. Víctor
    March 12, 2012 at 3:51 am

    Thanks, this work perfect. It’s the best solution I found.

  67. nycdavey
    March 7, 2012 at 10:15 pm

    This is awesome, thanks!

    I’m trying to add a “YES, add me to your list” checkbox just above the “Submit” button, so that only people who WANT to be on the MailChimp list get added.

    I’m having trouble figuring how to check the value of my checkbox and only submit the contact info to MailChimp if the checkbox value is “YES”. Any thoughts?

    • mas
      March 8, 2012 at 2:30 am

      Just create a single check box and for example, name it “mailchimp-optin”. The form data passed by cf7 will only contain “mailchimip-optin” element in the form array data if it’s checked, so inside the function call, wrap everything into a simple conditional statement like this:


      function wpcf7_send_to_mailchimp($cfdata) {
      $formdata = $cfdata->posted_data;
      if ( $formdata['mailchimp-optin'] ) {
      ...the code...
      }
      }
      add_action('wpcf7_mail_sent', 'wpcf7_send_to_mailchimp', 1);

      If the check box is not checked, then nothing should happen. Let me know if it works!

      • nycdavey
        March 8, 2012 at 2:06 pm

        That works perfectly. Thank you!

      • nycdavey
        March 14, 2012 at 1:49 pm

        Hi mas,

        I have found that if a person is already a member of my MailChimp list, this code will not add them to a group.

        Example: A person has, in the past, used my site’s contact form (named “contact”), is subscribed to my MailChimp list and is part of the list’s group named “contact”. The same person returns several days later with another question, uses my site’s contact form, but this time checks the box that says “Yes! I want to receive your newsletter”, which SHOULD add them to the “newsletter” group in my MailChimp list. However, with the original code above, MailChimp will NOT update this person on my list to now be in groups “contact” and “newsletter”. MailChimp will simply see that the person is a member of my list (and is part of the list’s group named “contact”) and not take action.

        I’m not experienced with the MailChimp API, but I think I’d have to come up with code that checks to see whether the person is already a list member, then check to see if the person is a member of a certain group, then add them to the list or group if they’re not already subscribed.

        Have you run into this scenario?

        • nycdavey
          March 14, 2012 at 2:22 pm

          I re-read the above and realized you clearly indicated the arguments for listSubscribe.

          By changing this line:

          $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false);

          To this:

          $retval = $api->listSubscribe($list_id, $send_this_email, $mergeVars, 'html', false, true, false);

          I appended the value “true” for “$update_existing” and “false” for “$replace_interests”.

          My apologies for cluttering up your page!

      • antonio
        September 28, 2012 at 3:37 am

        I’ve almost got this working totally. Can you post what a full code snippet with a checkbox included should look like?

        Thanks,

        Antonio

      • antonio
        September 28, 2012 at 3:57 am

        I finally got this working! Thanks sooo much

        • mas
          September 28, 2012 at 3:04 pm

          I’ve been meaning to update this post with few different versions of code but I haven’t gotten around to it. I’m glad you figured it out though…

  68. naama
    March 1, 2012 at 10:36 pm

    Great solution!
    Thanks so much!!

  69. Lisa Paitz Spindler
    March 1, 2012 at 7:13 pm

    Thanks for putting this together. It’s exactly what I need and a lifesaver. I’m going to tweet this blog post because I know there are other people who need to know how to do this as well.

    I would love to be able to add other address fields and a checkbox as well. However, the formatting requirements listed for other fields in MCAPI.class.php is a bit beyond my skill level. Is there any chance you might update this post to include how to do that? It would be the perfect solution for me if I could add that information. I need to add fields for address 1, address 2, city, state, zip, country and one checkbox.

    Thank you so much!

    • mas
      March 6, 2012 at 11:22 pm

      Thanks for the comment. I’m glad you found it useful. I didn’t really look into passing address values since I didn’t need to for my client, but when I get a chance, I’ll take a look and post an update.

      • Henry Cullen
        March 6, 2013 at 12:29 pm

        Just quickly but MailChimp is not instantaneous is it?
        You have to wait a bit before the data appears in your groups / list right?

        • mas
          March 14, 2013 at 1:50 am

          Hi Henry,
          From my experience, new contact gets added to MailChimp fairly quickly. Perhaps not “instantaneous”, but within a minute or two…