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);

COMMENTS

» Comments for this post are closed.

  1. Freezing

    I am sorry, but this is so beyond where I am. I signed up for MailChimp and uploaded the plugin. I’ve spent the last several hours trying to figure out what MailForm 7 is, and whether I create a list of people to invite to my blog or am creating a form letter that they receive when they do subscribe. I’ll keep at it, but I’m about to give up on WordPress.org in general. Thank you for your efforts, and I’m glad it has helped people, but I am still out in the cold…Sorry, I’m just frustrated and needed to say this. Not your problem.

  2. Adam

    nice article

    is there any similar clone also to wix users?

    i would like to extend to contact form on my Sound engineering site

    thanx

  3. Alan

    Hi Mas,
    Really great post… Thanks for all your hard work on this! Have you done anything similar for version 2 of mailChimp? I noticed that you refer to the old MCAPI mini v1.3.1. Would really like to see a post about mailChimp’s new api

    https://bitbucket.org/mailchimp/mailchimp-api-php/downloads

    Happy coding…

    All the best

    Alan

    1. mas

      Hi Alan,
      I apologize that this post is kind of old, but no – not really planning on doing update work at the moment.
      But if I do find time and motivation in the future, I’ll probably put up a separate post…
      best,
      Mas

  4. Robert

    Hi Mas,

    Hope this message finds you well. I just realized after testing a bit that my CF7 form submissions are no longer being added to MailChimp. I’m not sure how long this has been the case, but curious if other people have experienced something similar.

    Best,

    Robert

    1. RW

      Look down at “Mizzinc”‘s replies — CF7 has changed how you’re able to access the data.

      1. Robert

        @RW — you are a lifesaver!!! So glad I checked back during my round of troubleshooting today. Proper functionality has now been restored. 🙂

        Thanks again!!

  5. Jasmine

    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.

  6. Mizzinc

    CF7 V3.9

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

    1. Mizzinc

      Never mind, here is the answer.

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

  7. Steve Marks (BIOSTALL)

    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 🙂

  8. Danny van Kooten

    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

    1. Duecaz

      Really easy!
      Really Works!

    2. Alexandre

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

  9. Claire

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

  10. Chris

    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.

  11. Mike

    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!

  12. Peter

    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

  13. Nelson

    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…

  14. Jeff

    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.

  15. Luke

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

  16. James

    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?

    1. Andy Donnan

      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.

  17. Ricardo

    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í

    1. Profesor Yeow

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

  18. Talji

    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.

  19. Anthony

    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.

  20. Anthony

    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* 🙁

  21. Rob W

    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

  22. chema

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

  23. Radi

    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!

  24. Joris

    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!

    1. Steph

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

      1. Joris

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

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

        1. Claire

          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..

  25. Paul Hamon

    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!

  26. Bailey

    Thanks! This is great.

  27. Chris Dunst

    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

  28. Jeff

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

  29. Mabel

    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

    1. mas

      Hi Mabel,
      You want to put the MCAPI file in the folder for the theme that you are using. For example, if you are using TwentyTwelve theme, then you’d put the MCAPI file int he TwentyTwelve folder. Then, you want to add the code to the functions.php file inside of that theme folder.
      It will be a good idea to create a child theme if you are using a pre-made theme. That way, updating a theme won’t affect your custom code.
      http://codex.wordpress.org/Child_Themes
      http://wp.tutsplus.com/tutorials/theme-development/child-themes-basics-and-creating-child-themes-in-wordpress/

  30. Kun

    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!

  31. robb luther

    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…

    1. robb luther

      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);

    2. mas

      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.

      1. Robb Luther

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

  32. JT

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

    Thank you. 😉

  33. Jonny V

    Copy, paste, job done.

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

  34. David

    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);

    1. mas

      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

    2. David

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

      1. mas

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

  35. John

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

    1. mas

      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!

      1. John

        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 32×15 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.

        1. mas

          Just trying to be clear:
          [text* phone 32×15 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…

  36. John

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

  37. Rashed

    Great !!! Worked like a charm 🙂

  38. Chris

    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

    1. Rock

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

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

  39. Manzurul Haque

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

    1. mas

      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.

  40. Robert

    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

    1. mas

      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…

      1. Robert

        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

  41. Dre

    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!

    1. mas

      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

      1. Dre

        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!

        1. mas

          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!

          1. Kristy

            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.

          2. Ricardo

            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.

  42. Jill

    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!

    1. mas

      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!

  43. Eytan

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

    1. mas

      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.

  44. Jody Bailey

    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!

    1. nicole

      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?

  45. Eric

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

  46. Avery Z Chipka

    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”]

    1. Avery Z Chipka

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

      1. Avery Z Chipka

        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.

  47. Flash Buddy

    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.

  48. Matthew

    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!

  49. Zack

    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

    1. mas

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

      1. Zack

        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?

      2. Zack

        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

        1. mas

          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!

          1. Zack

            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

  50. mas

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

  51. Eli

    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!!

    1. mas

      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.

      1. Eli

        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!

        1. mas

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

    2. Flash Buddy

      Worked in the child theme directory for me.

  52. Andrea Bradley

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

  53. Daniel

    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

    1. mas

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

  54. Laurence

    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.

    1. Andrea Bradley

      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'),
      )

    1. Laurence

      Thanks for the post. This is really useful.

    2. mas

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

  55. Fawn

    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?

  56. Richard Young

    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

    1. mas

      Glad you figured it out!

    2. Eli

      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.

  57. Alex

    Can this tweak work for another form?

    1. mas

      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…

  58. Elena

    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!

  59. Jill

    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!

  60. Ulrik Foldager

    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!

    1. mas

      Hi Ulrik,

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

      mas

      1. Ulrik Foldager

        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.

  61. Rob Scott

    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

    1. mas

      You’re welcome!

  62. Dave

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

  63. ib

    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

    1. mas

      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…

      1. ib

        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.

        1. Jeremy

          Hi ib,

          thanks got it to worked by removing the groupings.

          and thank you Masahiko!

          1. Michael Caputo

            This worked for me as well.

            Thanks for the instructions!

        2. Angela

          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!

  64. peter

    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.

    1. mas

      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…

  65. Chris Demetriad

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

  66. brian

    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);

  67. Phil

    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?

    1. mas

      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.

      1. Phil

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

        1. David

          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

  68. Víctor

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

  69. nycdavey

    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?

    1. mas

      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!

      1. nycdavey

        That works perfectly. Thank you!

      2. nycdavey

        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?

        1. nycdavey

          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!

      3. antonio

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

        Thanks,

        Antonio

      4. antonio

        I finally got this working! Thanks sooo much

        1. mas

          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…

  70. naama

    Great solution!
    Thanks so much!!

  71. Lisa Paitz Spindler

    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!

    1. mas

      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.

      1. Henry Cullen

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

        1. mas

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

View All Comments ▾