MailChimp Integration with Contact Form 7 Plugin

Contact Form 7 is no doubt one of the most popular plugins on WordPress. At the time of writing this article, the plugin has 5+ million active installations. Its popularity lies in its simplicity, easy configuration, and flexibility. One can extend the plugin to their needs without touching the plugin code.

Recently, one of our readers asked about MailChimp integration with Contact Form 7 plugin. They want to use the Contact Form 7 plugin for the newsletter form. It has an email field and on the successful submission of a form, the entered email should add to their MailChimp subscriber list.

Contact Form 7 provides custom DOM events to extend its functionality. Using one of their Dom events which is ‘wpcf7mailsent’ you can integrate the MailChimp subscription code.

Get MailChimp API Key and Audience ID

Before we actually start writing code, you need to first grab your MailChimp API key and Audience ID which will be required in the code. Grab these details by following the steps below.

Login to your MailChimp account. From the user icon, select the Account.

account-link

On the next page, Click on Extra->API keys.

Click API Keys

Under the Your API keys section, click on Create A Key and copy your API key.

Copy API Key

Next, get an Audience ID to which you need to add your subscribers. For this, click on the Audience menu and then select the option Settings from the Manage Audience drop-down.

audience

Under the Settings click on the Audience name and defaults.

audience-name-defaults

On the next page, you will find your Audience ID.

Audience ID

Create a Form using Contact Form 7 Plugin

Once you are ready with your MailChimp credentials, the next thing you need to do is create your subscription form. Go to the ‘Contact Forms’ menu and create it. Your code will be something like the screenshot below.

newsletter form

As we are dealing with a newsletter form, let’s set the success message which can match with your end goal. Go to the ‘Messages’ tab and set it like below.

success message

Now, copy your created shortcode and place it wherever you want and you will see the form with an email field and submit button. Our end goal is when users enter an email and hit the submit button, this email will add to your MailChimp subscriber list. Let’s write a code for it.

Add JavaScript File in WordPress

As said before, I am going to use the Dom event ‘wpcf7mailsent’ of the Contact Form 7 plugin. It means we need to write a little piece of JavaScript code. First, it needs to include a JS file, say custom.js in your WordPress site. We also need to use Ajax so I will attach a WordPress Ajax URL and nonce to the JS file. In your active themes functions.php add the below code.

<?php
...
...
function custom_enqueue_scripts() {
   // Register the script
    wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array(), false, true );

    // Localize the script with new data
    $script_data_array = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'security' => wp_create_nonce( 'subscribe_user' ),
    );
    wp_localize_script( 'custom-script', 'blog', $script_data_array );

    // Enqueued script with localized data.
    wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'custom_enqueue_scripts' );

The above code includes custom.js file on the site and attaches the Ajax URL, nonce key to the ‘blog’ variable.

Your custom.js file will have the following JavaScript code.

document.addEventListener( 'wpcf7mailsent', function( event ) {

    if ( 'YOUR_CONTACT_FORM_ID' == event.detail.contactFormId ) {
        var inputs = event.detail.inputs;

        for ( var i = 0; i < inputs.length; i++ ) {
            if ( 'your-email' == inputs[i].name ) {

                var data = {
                    'action': 'subscribe_user_by_ajax',
                    'email': inputs[i].value,
                    'security': blog.security
                };
                jQuery.post(blog.ajaxurl, data, function(response) {
                    console.log(response);
                });
                break;
            }
        }
    }
}, false );

Replace the placeholder ‘YOUR_CONTACT_FORM_ID’ with your actual value. You can get this ID from the shortcode of your contact form. This is required because our code should execute only on the newsletter form and not on the other contact forms.

contact-form-id

The string ‘your-email’ is the name I have given to my email field. It remains as it is. If you noticed I have used the action as ‘subscribe_user_by_ajax’ which will be used to call our Ajax callback method where I will write a code for MailChimp subscription.

MailChimp Integration with Contact Form 7 Plugin

So far we created a newsletter form, wrote a JS code that will execute on the successful submission of a form. The next part is to take an email and send it to MailChimp using the MailChimp API. In the JS code, we used the ‘subscribe_user_by_ajax’ action so let’s write an Ajax callback code for it.

Add the below code in your theme’s functions.php file.

<?php
...
...

function subscribe_user_by_ajax_callback() {
    check_ajax_referer('subscribe_user', 'security');
    $email = $_POST['email'];
    $audience_id = 'YOUR_MAILCHIMP_AUDIENCE_ID';
    $api_key = 'YOUR_MAILCHIMP_API_KEY';
    $data_center = substr($api_key,strpos($api_key,'-')+1);
    $url = 'https://'. $data_center .'.api.mailchimp.com/3.0/lists/'. $audience_id .'/members';
    $auth = base64_encode( 'user:' . $api_key );
    $arr_data = json_encode(array(
        'email_address' => $email,
        'status' => 'subscribed' //pass 'subscribed' or 'pending'
    ));

    $response = wp_remote_post( $url, array(
            'method' => 'POST',
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => "Basic $auth"
            ),
            'body' => $arr_data,
        )
    );

    if ( is_wp_error( $response ) ) {
       $error_message = $response->get_error_message();
       echo "Something went wrong: $error_message";
    } else {
        $status_code = wp_remote_retrieve_response_code( $response );
        switch ($status_code) {
            case '200':
                echo $status_code;
                break;
            case '400':
                $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
                echo $api_response['title'];
                break;
            default:
                echo 'Something went wrong. Please try again.';
                break;
        }
    }
    wp_die();
}
add_action('wp_ajax_subscribe_user_by_ajax', 'subscribe_user_by_ajax_callback');
add_action('wp_ajax_nopriv_subscribe_user_by_ajax', 'subscribe_user_by_ajax_callback');

Make sure to replace placeholders ‘YOUR_MAILCHIMP_AUDIENCE_ID’ and ‘YOUR_MAILCHIMP_API_KEY’ with your actual MailChimp credentials. The above code takes an email and sends it to the API endpoint of the MailChimp subscription. I also set status as ‘subscribed’ which means the email will directly get subscribed to your list. If you want to send a confirmation email to the user to confirm their subscription then set the status as ‘pending’.

It’s all about MailChimp integration with Contact Form 7 Plugin. I hope you liked the tutorial. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

2 thoughts on “MailChimp Integration with Contact Form 7 Plugin

  1. Hi,

    Is there a way to add a checkbox to the contact form instead of just adding the email directly to Mailchimp? I’d like to make the subscription optional.

    Thank you for the article.

Leave a Reply

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