MailChimp Integration in WordPress Without Using a Plugin

When it comes to WordPress you will get almost every kind of plugin that works as per your expectation. Using plugins on the WordPress website is of course not a problem until you are not overloading your website with a bunch of plugins. If you have a large number of plugins on your WordPress website then definitely it will affect your server, website, cause conflicts between plugins. It may also slow down your website.

At Artisans Web, I always recommend the users to use minimum plugins as much as possible. If you can achieve your stuff by writing your own code then go for it. It’s always a good practice rather than using a plugin. By writing your own code, you will become a better WordPress developer. After all, it is key to become an expert in WordPress development.

In this article, we study how to do MailChimp integration in WordPress without using any plugin. We are going to create our own newsletter form, submit a form through WordPress Ajax, subscribe the user to your MailChimp’s Audience List.

Get MailChimp API Key and Audience Id

In order to get started with MailChimp integration in WordPress, you first need to get the MailChimp API key and the Audience ID. 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 which we need in a moment.

Copy API Key

Now you have your API key ready. 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 WordPress Shortcode

Our end goal is to create a working newsletter form so your visitors can become your MailChimp audience. For that, you first need to create a static form that has 2 fields – email and a submit button. Let’s create a shortcode that renders this form and you can place this newsletter form anywhere on your website using the shortcode.

Open your active themes functions.php file and add code below in it.

add_shortcode('mailchimp', 'mailchimp_form');
function mailchimp_form() {
    ob_start();
    ?>
    <form class="form-inline">
        <div class="form-group mb-2">
            <label for="email" class="sr-only"><?php _e('Email'); ?></label>
            <input type="email" class="form-control-plaintext" id="email">
        </div>
        <button type="button" class="btn btn-primary mb-2 subscribe"><?php _e('Subscribe'); ?></button>
    </form>
    <?php
    return ob_get_clean();
}

After adding the above code, you are now able to use the shortcode [mailchimp]. Place it wherever you want and you should see the subscription form. Of course, you may need to add your own styling to a form as per your website design.

To our form, we have added the id ’email’ to the email field and class ‘subscribe’ to the submit button. This id and class will be in use when we submit a form through Ajax.

Add JavaScript File in WordPress

As we intend to use WordPress Ajax, we have to write some JavaScript code. So, we need to include a JS file in the WordPress environment. WordPress provides a standard way to include the JS file which we should follow. Create a js/awscript.js file in your theme directory. To our JS file, we will pass our own variable ‘security’ which acts like a nonce.

Below code also goes inside functions.php file.

add_action( 'wp_enqueue_scripts', 'twentynineteen_scripts' );
function twentynineteen_scripts() {
    // Register the script
    wp_register_script( 'awscript', get_stylesheet_directory_uri() . '/js/awscript.js', array('jquery') );

    // Localize the script with new data
    $script_array = array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'security' => wp_create_nonce("subscribe_user"),
    );
    wp_localize_script( 'awscript', 'aw', $script_array );

    // Enqueued script with localized data.
    wp_enqueue_script( 'awscript' );
}

Now head over to js/awscript.js and write a code that takes user-entered email, passes it to Ajax, and shows the response to the user.

jQuery(function($){
    $('body').on('click', '.subscribe', function(e) {
        e.preventDefault();
        email = $('#email').val();
        if(isEmail(email)) {
            var data = {
                'action': 'subscribe_user',
                'email': email,
                'security': aw.security
            };

            $.post(aw.ajaxurl, data, function(response) {
                if (response == 200) {
                    alert('You have subscribed successfully.');
                } else {
                    alert(response);
                }
            });
        } else {
            alert('This is not a valid email');
        }
    });
});

function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

In the above code, apart from handling Ajax response I also added a function isEmail() which will check if the passed email is valid or not.

Add Subscriber To MailChimp Audience

So far we are done with our newsletter form and an Ajax call. Now write a code that actually sends an email to the MailChimp API and adds a subscriber to the MailChimp Audience ID.

Here as we need to give an API call we will use wp_remote_post method for sending requests and handling responses.

You should add the below code in the functions.php file.

add_action('wp_ajax_subscribe_user', 'subscribe_user_to_mailchimp');
add_action('wp_ajax_nopriv_subscribe_user', 'subscribe_user_to_mailchimp');

function subscribe_user_to_mailchimp() {
    check_ajax_referer('subscribe_user', 'security');
    $email = $_POST['email'];
    $audience_id = 'YOUR_AUDIENCE_ID';
    $api_key = 'YOUR_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();
}

While adding the code above, make sure to replace the placeholders YOUR_AUDIENCE_ID and YOUR_API_KEY with the actual values. The above code calls the MailChimp API and adds the email to the audience list directly. If you intend to send a confirmation email to the user before adding their email to the list then set a status value as ‘pending’.

Mailchimp also provides the Audience fields. Using these fields you can store extra information about users directly inside the MailChimp dashboard. Just in case, if you are looking to add Audience fields then you can do it by adding one more array element in the above POST request. Here, I am adding values for the default Audience fields FNAME and LNAME.

<?php
...
...
$arr_data = json_encode(array(
    'email_address' => $email,
    'status' => 'subscribed', //pass 'subscribed' or 'pending'
    'merge_fields'  => array(
        'FNAME' => 'ENTER_FIRST_NAME',
        'LNAME' => 'ENTER_LAST_NAME'
    )
));

It’s all about MailChimp integration in WordPress without plugins. I recommend this way as it gives you the freedom to style your form and also helps you to learn a bit about WordPress coding. Please share your thoughts or suggestions in the comment section below.

Related Articles

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

5 thoughts on “MailChimp Integration in WordPress Without Using a Plugin

  1. It works perfectly, thank you.
    I did a few changes in order to avoid using alerts, so the user will see the response below the input form.

    I have a quick question. Is it possible to integrate this to an existing contact form or WooCommerce checkout using a checkbox?

    Thanks!

  2. Hey Sajid,

    Got this working fine! Thanks very much.

    I was wondering if there a way to save people’s names as well as the email addresses. As in MailChimp you only save the email and not their full name.

    Andrew

    1. You can simply store name and email in the database. In that case, write the insert query in the ajax method and you are done.

      1. Hey Sajid,

        Thanks for the reply! I’ve given it a go myself, but my coding skills are pretty basic. I’ve got everything else working. I just don’t know how to insert the query in the ajax.

        Cheers

Leave a Reply

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