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 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 website then definitely it will affect your server, and cause conflicts between plugins. It may also slow down your website.

At Artisans Web, I always recommend users 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 plugins. We are going to create our own newsletter form, submit a form through WordPress Ajax, and subscribe the user to the desired Audience List of Mailchimp.

Get Mailchimp API Key and Audience ID

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. Click the user icon and then select the Account.

account-link

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

Click API Keys

Under Your API keys section, click on Create A Key and copy your API key which we need in a moment.

Copy API Key

Next, get an Audience ID to which you need to add your subscribers. For this, click on the Audience menu and 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 so your visitors can become your Mailchimp audience. For that, you first need to create the HTML form having 2 fields – email and a submit button. Let’s create a shortcode that renders this form. You can place the newsletter form anywhere on your website using the shortcode.

Open your functions.php file and add the code below to it.

add_shortcode('mailchimp', 'mailchimp_form');
function mailchimp_form() {
    ob_start();
    ?>
    <form id="frmSubscription">
        <input type="email" name="email" id="email" placeholder="Email" required />
        <p><button type="submit" name="submit">Subscribe</button></p>
    </form>
    <?php
    return ob_get_clean();
}

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

To the form, I have added the ids ’email’ to the email field and ‘frmSubscription’ to the form. These ids 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. It requires including 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 this JS file, I will pass the variable ‘security’ which acts like a nonce.

The below code also goes inside functions.php file.

add_action( 'wp_enqueue_scripts', 'blog_scripts' );
function blog_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 the user-entered email, passes it to Ajax, and shows the response to the user.

jQuery(function($){
    $('body').on('submit', '#frmSubscription', function(e) {
        e.preventDefault();

        var data = {
            'action': 'subscribe_user',
            'email': $('#email').val(),
            'security': aw.security
        };

        $.post(aw.ajaxurl, data, function(response) {
            if (response == 200) {
                alert('You have subscribed successfully.');
                $('#frmSubscription')[0].reset();
            } else {
                alert(response);
            }
        });
    });
});

In the above code, we are giving a call to Ajax on form submission. We are posting data like action, email, and security to the Ajax script.

Add Subscriber To Mailchimp Audience

So far we are done with the 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.

As we need to give an API call I will use the wp_remote_post() method for sending requests and handling responses.

For this 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 this code, make sure to replace the placeholders YOUR_AUDIENCE_ID and YOUR_API_KEY with the actual values. This code calls the Mailchimp API and adds the email to the audience list directly. If you want to send a confirmation email to the user before adding their email directly to the list, set a status value as ‘pending’.

Mailchimp also provides the Audience fields. Using these fields you can store extra information about users 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. Give it a try and share your thoughts in the comment section below.

Related Articles

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

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

    1. Hi,
      Even tho this was quite som time ago. May I ask how you did the change to avoid using alerts so the user can see the response below the input form?

      Thanks!

      1. Assuming you have an empty div with class success you can write something like
        $(‘.success’).html(‘your_message’);

  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 *