MailChimp Integration with Contact Form 7 Plugin

Contact Form 7 is one of the most popular plugins among WordPress users. 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 achieve a certain flow without touching the plugin’s code.

Using its extensibility, I also developed a plugin that connects Contact Form 7 with Google Sheets. It sends entries from your contact form to Google Sheets. It helps to keep track of your contact form data in one place.

Apart from Google Sheets, you can also establish a connection with other services like MailChimp. Recently, one of the readers asked about MailChimp integration with the Contact Form 7 plugin. They want to use the Contact Form 7 plugin for newsletter purposes. The form has an email field and on the submission of a form, the entered email should add to their MailChimp subscriber list.

To add a bridge between MailChimp and Contact Form 7, we can use the custom DOM events provided by the plugin. There are a few DOM events out of which the one which is needed is wpcf7mailsent event. With the help of this event, we fire the code to add emails to the MailChimp list.

For MailChimp integration, it requires you to send a POST request to the MailChimp API endpoint. And to communicate with the MailChimp APIs, you need to pass the API key and Audience ID. Let’s first grab it.

Get MailChimp API Key and Audience ID

Login to your MailChimp account. From the user icon, select 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 build your form. Your code will be something like the screenshot below.

newsletter form

As we are creating a form for the newsletter, let’s set the success message that matches the subscription. Go to the ‘Messages’ tab and set it like below.

success message

Next, copy the form shortcode and place it wherever you want and you will see the form with an email field and submit button. The visual part is completed. Now, the end goal is when users submit the email, it will add to the MailChimp subscriber list. To achieve it, we have to write code in both JavaScript and PHP.

Add JavaScript File in WordPress

As we want to use the wpcf7mailsent event of the Contact Form 7 plugin, let’s create a custom.js file and include it in the WordPress environment. We also need to use Ajax so I will attach an admin-ajax.php URL and nonce(to protect CSRF attacks) to this JS file. In your active themes functions.php add the below code.

function blog_scripts() {
    // Register the script
    wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), false, true );
  
    // Localize the script with new data
    $script_data_array = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'security' => wp_create_nonce( 'newsletter' ),
    );
    wp_localize_script( 'custom-script', 'blog', $script_data_array );
  
    // Enqueued script with localized data.
    wp_enqueue_script( 'custom-script' );
}
add_action('wp_enqueue_scripts', 'blog_scripts');

The above code includes custom.js file on the front end of your WordPress site. Here, I used 2 keys ajaxurl and security which are attached 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 given to the email field. The action ‘subscribe_user_by_ajax’ will be used to execute the server-side PHP function. This function will have the code for a MailChimp subscription.

MailChimp Integration with Contact Form 7 Plugin

We have created a newsletter form and added the DOM event that will execute on the successful submission of a form. The next part is to send the email to the MailChimp list through the MailChimp API. In the JS code, we used the ‘subscribe_user_by_ajax’ action, let’s add the ‘wp_ajax_{action}’ for it. The code will go inside the functions.php file.

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

Finally, define the callback method subscribe_user_by_ajax_callback() which performs the below steps.

  • Check if the nonce is valid. For the invalid nonce, the rest code will not be executed.
  • Use wp_remote_post() method to call the MailChimp API endpoint along with the required parameters like email.
function subscribe_user_by_ajax_callback() {
    check_ajax_referer('newsletter', 'security');
    $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' => $_POST['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();
}

Make sure to replace placeholders with the actual values. The above code sends an email to the API endpoint of the MailChimp list. Here, I set the status value as ‘subscribed’ which means the email will directly get subscribed to your list. If you want to send a confirmation email to the user before subscribing to the list, set the status value to ‘pending’.

It’s all about MailChimp integration with Contact Form 7 Plugin. I hope you can now easily integrate the MailChimp newsletter with the Contact Form 7 plugin. 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 *