DEV Community

Cover image for Custom Mailchimp Integration: A Guide for WordPress and Laravel
Shimanta Das
Shimanta Das

Posted on

Custom Mailchimp Integration: A Guide for WordPress and Laravel

Mailchimp helps small businesses do big things, with the right tools and guidance every step of the way. We’ve got everything you need to create multichannel campaigns that reach and resonate with your people.
When you are building a wordpress website, newsletter subscription is an important part. This section basically exists in the footer area.

For integrating the newsletter section inside the wordpress site, one of the best providers is “MailChimp”. For integrating mailchimp service as newsletter into wordpress , we mostly use the plugin “MC4WP: Mailchimp for WordPress”.

Image description

But here I will show you how you can custom mailchimp newsletter using PHP and Curl.

Step 1: Create an account on mailchimp and generate an api key for yourself. You can visit account on “https://admin.mailchimp.com/account/api/”

Image description

Step 2: Now go to your wordpress project, and go to your HTML newsletter section which you will integrate with the wordpress template page.

template-name.php

<form id="form1">
            <div class="mb-3">
                <label for="exampleInputEmail1" class="form-label">Email address</label>
                <input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp">

                <br>

                <div id="emailHelp" class="form-text" style="font-size:20px;">We'll never share your email with anyone else.</div>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>


<script>
    var ajaxurl = "<?php echo admin_url('admin-ajax.php') ?>";

    jQuery('#document').ready(function () {
        jQuery('#emailHelp').hide();
        jQuery('#form1').submit(function (e) {
            e.preventDefault();
            jQuery('#emailHelp').hide();

            let formdata = new FormData(this);

            if(formdata.get("email")){
                jQuery.ajax({
                type: "POST",
                url: ajaxurl,
                data: {
                    action: 'newsletter_subscription',
                    email:formdata.get('email'),
                },
                success: function (response) {
                    jQuery('#emailHelp').show();
                  if(response == "success"){
                    jQuery('#emailHelp').text(response);
                  }else{
                    jQuery('#emailHelp').text(response);
                  }
                },
                error:function(response){
                    jQuery('#emailHelp').show();
                    jQuery('#emailHelp').text("Please enter your valid email id.");
                }
            });
            }else if(formdata.get("email") == null || formdata.get("email") == ""){
                jQuery('#emailHelp').show();
                jQuery('#emailHelp').text("Please enter your valid email id.");
            }

        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Now, go to your project’s functions.php file and paste the code below … But make sure which parameter(‘subscribed’ or ‘pending’) you passed with your audience list url. I have mentioned their usages by code below.

functions.php

add_action('wp_ajax_newsletter_subscription', 'mailchimp_user');
add_action('wp_ajax_nopriv_newsletter_subscription', 'mailchimp_user');

function mailchimp_user()
{
    $email = $_POST['email'];
    $api_key = '0ff83cebe06aa1638d3703136c7094d0-us13';
    $data_center = substr($api_key, strpos($api_key, '-') + 1);
    $url = 'https://' . $data_center . '.api.mailchimp.com/3.0/lists/';

    try {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        // fetch the list id from the response
        if ($status_code === 200) {
            $response = json_decode($result, true);
            if (!empty($response['lists'])) {
                $list_id = $response['lists'][0]['id'];
            }
        }


        try {
            /**
             * pending -> means a confirmation mail will goes to email address for confirmation
             * subscribed -> means no need for confirmation and it will automatically saved audiences/lists/contacts in mailchimp 
             */
            $json = json_encode([
                'email_address' => $email,
                'status' => 'pending',
            ]);
            $url = 'https://' . $data_center . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members';
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
            $result = curl_exec($ch);
            $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $arr = json_decode($result, true);
            if ($arr['title'] == "Member Exists") {
                echo "This email id already exist! You may check your mail's inbox of $email ";
            }
            else if (200 == $status_code) {
                echo "An confirmation email has been sent to $email ";
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }


    } catch (Exception $e) {
        echo $e->getMessage();
    }

    wp_die();
}        
Enter fullscreen mode Exit fullscreen mode

Note: After proper subscription you will find the subscriber inside your audience tab. For more visit mailchimp audience url “admin.mailchimp.com/audience/contacts/”

Image description

Top comments (0)