How to Integrate MailChimp with Contact Form 7 {updated}

Written by: Ivan in How-To, Web Technology

How to Integrate MailChimp with Contact Form 7

With all the latest website updates, we also wanted to add a “Subscribe to our Newsletter” feature that would integrate seamlessly with MailChimp.

Finding a Sign Up widget was easy, and even though there were a few options available, we decided to go with MailChimp Widget. But we still needed to integrate the sign up process into our existing contact form from Contact Form 7. We wanted to add a “Subscribe to Our Newsletter” checkbox that will deliver the emails right into our MailChimp mailing list.

After looking for a Plugin that will let us do that easily, we  turned into different integration alternatives.

The good thing about MailChimp is that it has a great API library with lots of tips and tutorials. We found one that  worked perfect for what we had in mind; mcapi-merge-subscribe.zip


The Integration Process

1. At first lets add a “Subscribe” checkbox.

Here is the example of our finished Contact Form:

<div>Your Name (required)<br />[text* your-name]</div>
<div>Your Phone<br/>[text your-phone]</div>
<div>Your Email (required)<br />[email* your-email]</div>
<div>Your Message<br />[textarea your-message]</div>
<div>Subscribe to our Newsletter [checkbox subscribe default:1 "yes"]</div>
<div>[captchac captcha-865 size:l] [captchar captcha-865]</div>
<div>[submit "Contact Us"]</div>

Go to your Contact Form Admin Panel and open the form you want to edit. Generate a new Checkbox tag.  Put the tag name; in our case subscribe.  “Default:1″ will generate a checkbox that is selected by default. The “yes” will create a label beside that checkbox.

For this to work, you need to add in this line of code:

<div>Subscribe to our Newsletter [checkbox subscribe default:1 "yes"]</div>

2. Now we can download the mcapi-merge-subscribe.zip file. We will be working with the code from: store-address.php and MCAPI.class.php. Copy the MCAPI.class.php into the includes(see #3) folder. This file is needed for the verification process.

Updated May 27th.

Note: If you have another MailChimp plugin already installed on your WordPress site, you don’t necessarily need to copy the mcapi.class.php. All you have to do is find where it is located within the MailChimp plugin folder and then link to it ( your path might be different ):

require_once('../../mailchimp-widget/lib/mcapi.class.php');

3. Open the controller.php. You can find it in: plugins -> contact-form-7 -> includes -> controller.php.

Updated March 18th.

Note: There are two ways to submit the Contact Form 7 form: with Ajax, or without.

Ajax Submission

On line 76 look for:

} elseif ( $wpcf7_contact_form->mail() ) {
 $items['mailSent'] = true;
 $items['message'] = wpcf7_get_message( 'mail_sent_ok' );

No Ajax Submission

On line 131 look for:

} elseif ( $wpcf7_contact_form->mail() ) {
 $_POST['_wpcf7_mail_sent'] = array( 'id' => $id, 'ok' => true, 'message' => wpcf7_get_message( 'mail_sent_ok' ) );
 do_action_ref_array( 'wpcf7_mail_sent', array( &$wpcf7_contact_form ) );
 $wpcf7_contact_form->clear_post();
 }

Those parts of code is responsible for successful form submission, and we would want to include MailChimp’s subscription code here. This way the subscription process will start only if the form went through successfully.

4. Now we can start editing the form and copying  files, and editing the controller file. We will add an if statement to check if the checkbox was selected or not. Then in order to integrate the code with MailChimp we will get the API  Key, List Id, and change some variable names. The variables your-name and your-email well be grabbed from the form and passed on to MailChimp. 
When we are done with the necessary steps, the code should look like this:

Updated May 25th.

Ajax Submission

} elseif ( $wpcf7_contact_form->mail() ) {
 
 $items['mailSent'] = true;

if(isset($_POST['subscribe'][0])) {
 //IF CHECKED-  verify that subscribe box is checked
 require_once('MCAPI.class.php');
 // grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('YOUR 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 = "YOUR LIST ID";

// Merge variables are the names of all of the fields your mailing list accepts
 // Ex: first name is by default FNAME
 // You can define the names of each merge variable in Lists > click the desired list > list settings > Merge tags for personalization
 // Pass merge values to the API in an array as follows

$mergeVars = array('FNAME'=>$_POST['your-name']);

if($api->listSubscribe($list_id, $_POST['your-email'], $mergeVars) === true) {
// It worked! Display "mail_sent_ok" message and add the Confirmation note.                       

$items['message'] = (wpcf7_get_message( 'mail_sent_ok' )." <br/>Please check your email for a confirmation link." );

}else{
// An error ocurred, display "mail_sent_ok" message and add the Error note.                   

$items['message'] =   (wpcf7_get_message( 'mail_sent_ok' )." <br/>But there was a problem processing your submission." );
 }

}else{
 //IF NOT CHECKED-  jsut send the form  
 $items['message'] = wpcf7_get_message( 'mail_sent_ok' );
 } 

No Ajax Submission

} elseif ( $wpcf7_contact_form->mail() ) {

 do_action_ref_array( 'wpcf7_mail_sent', array( &$wpcf7_contact_form ) );            
 //IF CHECKED-  verify that subscribe box is checked
 if(isset($_POST['subscribe'][0])) {

 require_once('MCAPI.class.php');
 // grab an API Key from http://admin.mailchimp.com/account/api/
 $api = new MCAPI('YOUR 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 = "YOU LIST ID";

 // Merge variables are the names of all of the fields your mailing list accepts
 // Ex: first name is by default FNAME
 // You can define the names of each merge variable in Lists > click the desired list > list settings > Merge tags for personalization
 // Pass merge values to the API in an array as follows

 $mergeVars = array('FNAME'=>$_POST['your-name']);

 if($api->listSubscribe($list_id, $_POST['your-email'], $mergeVars) === true) {
 // It worked! Display "mail_sent_ok" message and add the Confirmation note.                        

 $_POST['_wpcf7_mail_sent'] = array( 'id' => $id, 'ok' => true, 'message' => ($wpcf7_contact_form->message( 'mail_sent_ok' )." <br/>Please check your email for a confirmation link.") );

 }else{
 // An error ocurred, display "mail_sent_ok" message and add the Error note                   

 $_POST['_wpcf7_mail_sent'] = array( 'id' => $id, 'ok' => true, 'message' =>  ($wpcf7_contact_form->message( 'mail_sent_ok' )." <br/>There was a problem processing your submission.") );

 }
 //IF NOT CHECKED-  just send the form    
 }else{ $_POST['_wpcf7_mail_sent'] = array( 'id' => $id, 'ok' => true, 'message' => $wpcf7_contact_form->message( 'mail_sent_ok' ) );

 }

 } else {
 $_POST['_wpcf7_mail_sent'] = array( 'id' => $id, 'ok' => false, 'message' => $wpcf7_contact_form->message( 'mail_sent_ng' ) );
 }

If you followed all the steps correctly on every form submission, a new user will be subscribed to your mailing list.

More Fields Note: If you want to pass more fields to MailChimp, you can find the answer here.

Hope this helps with your MailChimp integration. Please let us know if this tutorial was helpful, or if you have any notes and comments.

28 Responses to “How to Integrate MailChimp with Contact Form 7 {updated}”

  • James says:

    Hi Ivan,
    I am having some trouble getting this to work. Ive got a simple Contact 7 form that looks like this.

    Your Name (required) [text* your-name]
    Your Email (required) [email* your-email]
    Subscribe to our Newsletter [checkbox subscribe default:1 ""]
    [submit "Contact Us"]

    I’ve got mailchip-widget plugin running.

    I’ve updated both the ajax and non-ajax sections of controller.js to include MERGE2 (my tag for your-name), i’ve included the correct links for

    require_once(‘../../mailchimp-widget/lib/mcapi.class.php’);

    and I’ve added my API key for mail chimp and the unique ID for the list I am trying to subscribe to. When I fill in the simple form with the checkbox ticked, I just get the spinning arrows. My console is showing the errors –
    Uncaught TypeError: Object # has no method ‘ns_mc_widget’ &
    Uncaught TypeError: Cannot read property ‘into’ of null

    Any help would be great.
    James

    • Ivan says:

      Hi James
      I looked over your site, and have a few questions. Do you have the MailChimp widget plugin activated? Only the subscribe form on the home page works. I tried to submit an email from other pages but it wasn’t working, I couldn’t find any mention of it in the source either.
      Do you have the “Please check your email for a confirmation link.” added to the script? I submitted a form on the links page with the subscribe ckeckbox selected, but only got the “Thank you” message.
      Did you set the path to your MailChimp widget correctly? If that doesn’t help, try copying the mcapi.class.php into the includes folder.
      Let me know if it helps.

  • Rebecca says:

    Just in case it helps anyone in the future, MCAPI is case sensitive. I should have known…

    Regardless… THANK YOU SO MUCH for this! It is exactly what I needed to get my contact form working with mailchimp!

  • Hello Ivan,

    Thank you for this post, this is exactly what I was looking for!!!

    I made it work using your description and technic, but I had to erase the “…” on the last line code:
    $on_sent_ok = $wpcf7_contact_form->…
    Because wordpress told me there was a fatal error because of it!

    I have a problem, when people send me an email, it looks like it’s not sending because the arrow keep turning and because there is no messages displayed on the contact form (however I receive the contact form 7 notification and the mail chimp link to confirm my subsribtion)

    my form is there: http://gcbsourcing.com/En/Blog/contact

    Can anyone help me to know what’s wrong?

    Thanks again for the post :)

    • Ivan says:

      Hi there
      As per the $on_sent_ok = $wpcf7_contact_form->… – you don’t need to copy this line. It is there to show where to stop putting the code.
      If you did copy it, make sure you only have the original one: $on_sent_ok = $wpcf7_contact_form->additional_setting( ‘on_sent_ok’, false );
      It looks like you broke the Ajax sequence for the form submission, so just make sure all the contact form 7 code is in place.
      I took $on_sent_ok = $wpcf7_contact_form->… off the post
      Let me know if it helps.

    • Hello Ivan,

      I’m sorry about that, I never learn any programming… ha ha, you nust have think it was funny thinking that 3 dots could be programming…lol…

      Now I’m going to link mailchimp with my French blog. However I have the plugin “mailchimp” already installed on it. By reading the comments it seems like there is a problem with it?

      Is there something special I need to do for make it work?

      Kind regards,
      Nicolas

    • Ivan says:

      Hi Nicholas, it is great to hear that you got it to work.
      As per your FR Blog question – we have a MailChimp widget installed ( the little form in the footer ), but never had any errors come up.
      If errors do come up, try this:Check if your MailChimp plugin has its own mcapi.class.php. Then go to your Contact From 7 code and relink – require_once(‘MCAPI.class.php’); to the MailChimp Plugin file.
      I think I will add this part to the post.

    • Hi Ivan,

      I didn’t had to relink the Mcapi and it is working perfectly.

      Thank you very much for your help and your fast reply.

      Good luck in your business

  • Marijn says:

    Hi Ivan, great stuff, just what I needed and I got it working, which is a big deal for me ;-)

    One question left…my code knowledge is not to good. I want a first and a last name, so I need to add LNAME and ['last-name'], but this is not working:

    $mergeVars = array(‘FNAME’=>$_POST['first-name']);
    $mergeVars = array(‘LNAME’=>$_POST['last-name']);

    Please help!

    • Ivan says:

      Hi Marijn
      Try this:
      1. In the Contact Form 7 add the following field:
      <div>Your Last Name (required)[text* your-last-name]</div>
      2. To the $mergeVars add the following :
      $mergeVars = array('FNAME'=>$_POST['your-name'],
      'LNAME'=>$_POST['your-last-name']);

      That should do it.
      If you want to pass more information to MailChimp you need to add the fields in your MailChimp lists->settings->List Fields and *|MERGE|* Tags( e.g bellow – CITY), then add the required field to Contact Form 7 ( e.g. bellow – your-city), and after that connect them both with the $mergeVars. Quick example:
      <div>Your City (required)[text* your-city]</div>
      $mergeVars = array('FNAME'=>$_POST['your-name'],
      'CITY'=>$_POST['your-city']);

      Let me know if it works.

    • Marijn says:

      Hi Ivan,

      I made it like this, but unfortunately it won’t work…

      cheers, Marijn

    • Marijn says:

      Sorry..like this…

      $mergeVars = array(‘FNAME’=>$_POST['first-name'],
      ‘LNAME’=>$_GET['last-name'],
      ‘PHONE’=>$_GET['your-phonenumber']);

    • Ivan says:

      Hi Marijn
      The problem is the $_GET – I looked into the issue, and because of the way Contact Form 7 submits we need to use $_POST on all the new fields that we want to include with MailChimp integration. Tested it on our site, and it worked fine. Let me know if the $_POST change works for you.

    • Marijn says:

      IT’S WORKING!!!!

      Stuppid misstake…. Dreamweaver asked every time after saving the controller file if the links must be updated and I thought “ooh that’s a smart program, I should do that” ;-)

      Case solved!! Thanks a lot!

      Cheers, Marijn

  • annamarie says:

    I don’t seem to be able to get it to work. It bypasses the subscription process.

    I’ve spent hours looking at it trying to figure out what I am not doing right. I’m not a coder, just a WP user but I do want this functionality.

    • Ivan says:

      Hi Annamarie
      Can you please send me a link to the page you were putting the form on? I looked through your site, and could only see the Contact Form that seems to be provided by Mail Chimp itself.
      note: To put your Contact Form 7 in a side bar use Contact From 7 Widget

  • annamarie says:

    Yeah, I too have been trying to figure this out. I will go to work on its soon.

    Thank you very much for sharing.

  • TC says:

    THANK YOU! This is exactly what I was looking for, been trying to cobble all kinds of integration chains together via plug-ins, CRMs, APIs, etc., and this cuts right down to it. Lifesaver!

  • jason says:

    I got it working! I have some suggestions to help make your very useful article a little easier to follow.

    FIRST: If you have a Mailchimp plugin already installed, it this won’t work because the class “MCAPI” is alrady being declared and it cannot be redeclared. I had to deactivate my Mailchimp plugin to get past this error.

    SECOND: By default, Contact Form 7 collect a single “full name”, and Mailchimp collects AND REQUIRES both a first name and a last name. You have to go into Mailchimp and make sure last name is not required or the submission won’t work.

    Thanks!

    • Ivan says:

      Hi Jason,
      Addressing some of the issues you mentioned: The ellipse is there to show the last line of code that you need to be aware of; we have the MailChimp plugin installed but didn’t run into any issues; MailChimp will take a vast variety of fields (as many as you specify) , we decided to pass only the Full Name as FNAME (MailChimp tag) and the email, but we didn’t had to specify Last Name.
      Thanks for mentioning these issues as they may help others.

  • jason says:

    I figured out that error. I had the Mailchimp plugin installed, which was also declaring the MCAPI class. You may want to mention that in your article.

    Now I’m having a new problem… Your AJAX code example cuts off with an ellipse. I’m not sure what that means.

  • jason says:

    I’m trying to implement this at http://openskyfitness.com/contact/ and I can’t get it to work.

    I’m getting the following error when I submit the form: “Fatal error: Cannot redeclare class MCAPI in /home/content/42/3617942/html/wp-content/plugins/contact-form-7/includes/MCAPI.class.php on line 3″

    Any advice?

  • Fred says:

    Very valuable!!

    I really was struggling when having the Mailchimp script and the CF7 Script on one page. It was not working the ajax loader got stucked.

    Now it is working very smoothly and I have more control over what is happening.

    Cheers
    Fred

  • Wil says:

    Great tutorial, thanks a lot!

    Any chance you know of a good similar tutorial for those using Aweber?

    • Ivan says:

      Thanks Wil.
      I just looked into your Aweber question, found out few things. 1. They have a widget for WordPress. 2. They don’t allow/accept subscribers with another script. I found the topic on their support section.

  • Patrick says:

    Hey Ivan,

    Yeah I got it working now, thanks alot for the help!!!

    Regards, P

  • Patrick says:

    Really cool, this was exactly what I was looking for. I’ve completed all the steps, but I can’t seem to get it working. It seems like it just bypasses the subscription process everytime.

    Please help.

    Regards, Patrick

    PS. What should I do with the “store-address.php”, maybe that’s the issue?

    • Ivan says:

      Hi Patrick
      On Friday Mar 18, I updated the post with some new information about Contact Form 7 Ajax submission.
      I think your form uses Ajax for form submissions (from what I could see), so try using the Ajax Submission way.
      Let me know if it works or not.
      The store-address.php – really has no use to us. It was the file from which we used the code for MailChimp call outs and email subscription process.