Advertisement
  1. Web Design
  2. Email
  3. Email Templates

How to Create a Mailchimp Subscribe Form Widget for WordPress

Scroll to top
Read Time: 19 min

In this tutorial I’ll explain how to create a “Mailchimp subscribe form widget” using WordPress, the Mailchimp API, and AJAX. It will be aimed at competent beginner developers, and requires some understanding of PHP and WordPress development. There’s a lot to do, so let’s get stuck in!

A Quick Note on APIs

“The web has gotten really "API-ish". By that I mean, almost every major site is pushing and pulling content to and from other sites.” – Scott Fennell

I’ve covered APIs a couple of times in recent tutorials, so for a quick definition and to help you get up and running with REST APIs I recommend you take a look at these two resources:

As far as Mailchimp’s API and REST goes, from the documentation:

“Most APIs are not fully RESTful, including the Mailchimp API. But Mailchimp follows most of the practices and common definitions of the style. For example, the Mailchimp API has what we call “resources,” which are typically nouns like “subscribers” or “campaigns.” You take action on resources using the standard HTTP methods: POST, GET, PATCH, and DELETE.” 

Beginning the Mailchimp Subscribe Form Plugin

We will add our widget as a simple plugin called mailchimp-widget. I won’t describe in detail how to create a plugin, but I’ll provide some resources below to help you get started if you need them. Begin by creating a folder called mailchimp-widget and inside that folder create a mailchimp-widget.php file. Add the following File Header code snippet to the top of the file:

1
/*
2
    Plugin Name: Mailchimp widget
3
    Plugin URI: http://www.enovathemes.com
4
    Description: Mailchimp subscribe widget
5
    Author: Enovathemes
6
    Version: 1.0
7
    Author URI: http://enovathemes.com
8
*/
9
10
if ( ! defined( 'ABSPATH' ) ) {
11
    exit; // Exit if accessed directly
12
}

A REST API, as with any API, works with an API key. So at this point you’ll need a Mailchimp account, you’ll need to create a mailing list (nowadays referred to as an “audience”) and the API key. 

Mailchimp provides full and detailed information about how to generate your own API key. And as with any API, Mailchimp have also published very thorough documentation that we can refer to.

So here is our plan:

  1. First we will fetch your Mailchimp lists, so you can choose from the widget settings the list to which your users will be subscribed.
  2. Next we will build the widget itself.
  3. Then we will create the action that takes your user data from the Mailchimp subscribe form and sends it to Mailchimp using AJAX and the REST API.

Fetch the Mailchimp Lists

Let’s create a simple function that connects to the Mailchimp API using cURL, then caches the results in a WordPress “Transient” (a way to cache information).

At the top of your plugin add the Mailchimp REST API key as a constant:

1
define('MAILCHIMP_API', 'caa6f34b24e11856eedec90bc997a068-us12-my-fake-api');

Next, let’s create the Mailchimp connect function. The naming is optional, but should be descriptive.

1
mailchimp_connect( $url, $api_key, $data = array() ) {}

This function requires several parameters:

  • $url – the Mailchimp REST API endpoint
  • $api_key – our API key
  • $data – the data we have to transfer to Mailchimp.

Inside that function add the following code:

1
$url .= '?' . http_build_query($data);

As this function will be used to get results from Mailchimp, we need to build a query from our data and make it part of the url.

With that done we are ready to initialize a cURL connection. Add the following code after it:

1
$mailchimp = curl_init();

And now using the curl_setopt() function we can pass the parameters to the curl_init we created earlier.

1
$headers = array(
2
'Content-Type: application/json',
3
'Authorization: Basic '.base64_encode( 'user:'. $api_key )
4
);
5
6
curl_setopt($mailchimp, CURLOPT_HTTPHEADER, $headers);
7
curl_setopt($mailchimp, CURLOPT_URL, $url );
8
curl_setopt($mailchimp, CURLOPT_RETURNTRANSFER, true);
9
curl_setopt($mailchimp, CURLOPT_CUSTOMREQUEST, 'GET');
10
curl_setopt($mailchimp, CURLOPT_TIMEOUT, 10);
11
curl_setopt($mailchimp, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
12
curl_setopt($mailchimp, CURLOPT_SSL_VERIFYPEER, false);

Whoa, Slow Down There Cowboy

Fair enough, let me explain what is going on here! 

  • As with any REST API connection we will need to specify the content type we expect to get and make a simple authorization using our API key. That is all dealt with in the $headers variable. 
  • Next we set the URL option. 
  • CURLOPT_RETURNTRANSFER is where we tell the curl not to echo the result, but instead write it into variable. 
  • After that we set the request type; the Mailchimp API supports POST, GET, PATCH, PUT, and DELETE
  • Next we specify the timeout in seconds. 

Then the final two options you can ignore; we use them to specify the user agent and set false to certificate verification for TLS/SSL connection. 

Now we can execute the curl and return the results. The full function looks like this:

1
function mailchimp_connect( $url, $api_key, $data = array() ) {
2
3
    $url .= '?' . http_build_query($data);
4
5
    $mailchimp = curl_init();
6
7
    $headers = array(
8
    	'Content-Type: application/json',
9
		'Authorization: Basic '.base64_encode( 'user:'. $api_key )
10
	);
11
12
	curl_setopt($mailchimp, CURLOPT_HTTPHEADER, $headers);
13
	curl_setopt($mailchimp, CURLOPT_URL, $url );
14
	curl_setopt($mailchimp, CURLOPT_RETURNTRANSFER, true);
15
	curl_setopt($mailchimp, CURLOPT_CUSTOMREQUEST, 'GET');
16
	curl_setopt($mailchimp, CURLOPT_TIMEOUT, 10);
17
	curl_setopt($mailchimp, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
18
	curl_setopt($mailchimp, CURLOPT_SSL_VERIFYPEER, false);
19
20
    return curl_exec($mailchimp);
21
}

If no API key is provided you will see an error message where you would otherwise expect to see the subscribe list select. 

Construct the Endpoint URL

Next up, let’s create the Mailchimp url with the api endpoint:

1
$url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/';

Information on API endpoints can be found in the official Mailchimp documentation.

We now need to check if a transient already exists; if not we should make a new Mailchimp list fetch, otherwise we will return the results from transient. This way we can save resources with caching. If there are no results we will show an error message. If any API key is provided I always use it as a part of the transient name, as a way of ensuring unique naming.

1
if ( false === ( $mailchimp_list = get_transient( 'mailchimp-' . $api_key ) ) ) {
2
3
// List fetch here

4
5
}
6
if ( ! empty( $mailchimp_list ) ) {
7
return unserialize( base64_decode( $mailchimp_list ) );
8
} else {
9
return new WP_Error( 'no_list', esc_html__( 'Mailchimp did not return any list.', 'mailchimp' ) );
10
}

Fetch Mailchimp Lists

So now let’s fetch the Mailchimp list. Add the following code:

1
$data = array('fields' => 'lists','count' => 'all',);         
2
$result = json_decode( mailchimp_connect( $url, 'GET', $api_key, $data) );

Here we send a request to Mailchimp using our previously created function mailchimp_connect() to get all the lists available. And as the result is required in JSON format we’ll need to decode it.

First let’s make sure that we have the results, otherwise we’ll display the error message:

1
if (! $result ) {
2
return new WP_Error( 'bad_json', esc_html__( 'Mailchimp has returned invalid data.', 'mailchimp' ) );
3
}
4
if ( !empty( $result->lists ) ) {
5
foreach( $result->lists as $list ){
6
$mailchimp_list[] = array('id'      => $list->id, 'name'    => $list->name,);
7
}
8
} else {
9
return new WP_Error( 'no_list', esc_html__( Mailchimp did not return any list.', 'mailchimp' ) );
10
}

After the error check, if we do have valid data and we have at least one Mailchimp list we add the Mailchimp list id and name to our mailchimp_list array. Lastly, if there is valid data, but no list, we display the second error message.

Now we need to encode, serialize and set the transient:

1
if ( ! empty( $mailchimp_list ) ) {$mailchimp_list = base64_encode( serialize( $mailchimp_list ) );
2
set_transient( 'mailchimp-' . $api_key, $mailchimp_list, apply_filters( 'null_mailchimp_cache_time', WEEK_IN_SECONDS * 2 ) );}

So the full function looks like this:

1
function mailchimp_list() {
2
3
    $api_key = MAILCHIMP_API;
4
5
    if (empty($api_key)) {
6
        return new WP_Error( 'no_api_key', esc_html__( 'No Mailchimp API key is found.', 'mailchimp' ) );
7
    }
8
     
9
10
    if ( false === ( $mailchimp_list = get_transient( 'mailchimp-' . $api_key ) ) ) {
11
12
        $data = array(
13
            'fields' => 'lists',
14
            'count' => 'all',
15
        );
16
         
17
        $result = json_decode( mailchimp_connect( $url, 'GET', $api_key, $data) );
18
       
19
        if (! $result ) {
20
            return new WP_Error( 'bad_json', esc_html__( 'Mailchimp has returned invalid data.', 'mailchimp' ) );
21
        }
22
23
        if ( !empty( $result->lists ) ) {
24
            foreach( $result->lists as $list ){
25
                $mailchimp_list[] = array(
26
                    'id'      => $list->id,
27
                    'name'    => $list->name,
28
                );
29
            }
30
        } else {
31
            return new WP_Error( 'no_list', esc_html__( 'Mailchimp did not return any list.', 'mailchimp' ) );
32
        }
33
34
        // do not set an empty transient - should help catch private or empty accounts.

35
        if ( ! empty( $mailchimp_list ) ) {
36
            $mailchimp_list = base64_encode( serialize( $mailchimp_list ) );
37
            set_transient( 'mailchimp-' . $api_key, $mailchimp_list, apply_filters( 'null_mailchimp_cache_time', WEEK_IN_SECONDS * 2 ) );
38
        }
39
    }
40
41
    if ( ! empty( $mailchimp_list ) ) {
42
        return unserialize( base64_decode( $mailchimp_list ) );
43
    } else {
44
        return new WP_Error( 'no_list', esc_html__( 'Mailchimp did not return any list.', 'mailchimp' ) );
45
    }
46
}

Build the WordPress Widget

As with plugin development basics, I won’t cover basic widget creation here, but ours will be a relatively simple widget and I will highlight the most important parts of it.

1
add_action('widgets_init', 'register_mailchimp_widget');
2
function register_mailchimp_widget(){
3
    register_widget( 'WP_Widget_Mailchimp' );
4
}
5
6
class  WP_Widget_Mailchimp extends WP_Widget {
7
8
	public function __construct() {
9
		parent::__construct(
10
			'mailchimp',
11
			esc_html__('* Mailchimp', 'mailchimp'),
12
			array( 'description' => esc_html__('Mailchimp subscribe widget', 'mailchimp'))
13
		);
14
	}
15
16
	public function widget( $args, $instance ) {
17
18
		wp_enqueue_style('widget-mailchimp');
19
		wp_enqueue_script('widget-mailchimp');
20
21
		extract($args);
22
23
24
		$title  = apply_filters( 'widget_title', $instance['title'] );
25
		$list   = $instance['list'] ? esc_attr($instance['list']) : '';
26
27
		$output = "";
28
		$output .= $before_widget;
29
		$output .='<div class="mailchimp-form">';
30
			if ( ! empty( $title ) ){$output .= $before_title . $title . $after_title;}
31
			
32
			$output .='<form class="et-mailchimp-form" name="et-mailchimp-form" action="'.esc_url( admin_url('admin-post.php') ).'" method="POST">';
33
				$output .='<input type="text" value="" name="fname" placeholder="'.esc_html__("First name", 'mailchimp').'">';
34
				$output .='<input type="text" value="" name="lname" placeholder="'.esc_html__("Last name", 'mailchimp').'">';
35
				$output .='<div>';
36
					$output .='<input type="text" value="" name="email" placeholder="'.esc_html__("Email", 'mailchimp').'">';
37
					$output .='<span class="alert warning">'.esc_html__('Invalid or empty email', 'mailchimp').'</span>';
38
				$output .= '</div>';
39
				
40
				$output .='<div class="send-div">';
41
			    	$output .='<input type="submit" class="button" value="'.esc_html__('Subscribe', 'mailchimp').'" name="subscribe">';
42
					$output .='<div class="sending"></div>';
43
				$output .='</div>';
44
45
			    $output .='<div class="et-mailchimp-success alert final success">'.esc_html__('You have successfully subscribed to the newsletter.', 'mailchimp').'</div>';
46
		        $output .='<div class="et-mailchimp-error alert final error">'.esc_html__('Something went wrong. Your subscription failed.', 'mailchimp').'</div>';
47
		        
48
		        $output .='<input type="hidden" value="'.$list.'" name="list">';
49
				$output .='<input type="hidden" name="action" value="et_mailchimp" />';
50
				$output .= wp_nonce_field( "et_mailchimp_action", "et_mailchimp_nonce", false, false );
51
52
			$output .='</form>';
53
		$output .='</div>';
54
		$output .= $after_widget;
55
		echo $output;
56
	}
57
58
 	public function form( $instance ) {
59
60
		$defaults = array(
61
 			'title' => esc_html__('Subscribe', 'mailchimp'),
62
 			'list'  => '',
63
 		);
64
65
 		$instance = wp_parse_args((array) $instance, $defaults);
66
67
 		$list_array = mailchimp_list();
68
69
 		?>
70
71
			<p>
72
				<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php echo esc_html__( 'Title:', 'mailchimp' ); ?></label> 
73
				<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr($instance['title']); ?>" />
74
			</p>
75
76
			<?php if ( is_wp_error( $list_array ) ): ?>
77
				<p><?php echo wp_kses_post( $list_array->get_error_message() ); ?></p>
78
			<?php else: ?>
79
				<p>
80
					<label for="<?php echo $this->get_field_id( 'list' ); ?>"><?php echo esc_html__( 'List:', 'mailchimp' ); ?></label> 
81
					<select class="widefat" id="<?php echo $this->get_field_id( 'list' ); ?>" name="<?php echo $this->get_field_name( 'list' ); ?>" >
82
					<?php foreach ( $list_array as $list ) { ?>
83
						<option value="<?php echo $list['id']; ?>" <?php selected( $instance['list'], $list['id'] ); ?>><?php echo $list['name']; ?></option>
84
					<?php } ?>
85
					</select>
86
				</p>
87
			<?php endif; ?>
88
		
89
	<?php }
90
91
	public function update( $new_instance, $old_instance ) {
92
		$instance = $old_instance;
93
		$instance['title'] = strip_tags( $new_instance['title'] );
94
		$instance['list']  = strip_tags( $new_instance['list']);
95
		return $instance;
96
	}
97
}

Here is the full widget code, paste it inside your plugin’s main file at the end. The most important parts are the public function widget, and public function form.

Public Function Form

Here, using our previously created function mailchimp_list(), we fetch the subscription lists from your account and create a select with the data, so when adding the widget you can choose the list to which you want your users to subscribe.

Public Function Widget

1
wp_enqueue_style('widget-mailchimp');
2
wp_enqueue_script('widget-mailchimp');

Before anything else we enqueue the script and style files for the widget, so go to the top of your plugin and add the code, right after the Mailchimp API constant.

1
function register_mailchimp_script(){
2
wp_register_script( 'widget-mailchimp', plugins_url('/js/widget-mailchimp.js', __FILE__ ), array('jquery'), '', true);
3
wp_register_style('widget-mailchimp', plugins_url('/css/widget-mailchimp.css', __FILE__ ));
4
}

Be sure to create the js and css folders referenced here, and create the corresponding widget-mailchimp.js/css files inside those folders. The JS file handles the AJAX request and the CSS file adds basic styling.

After that we create the Mailchimp subscribe form structure itself. Here we have three fields visible to the user: 

  1. the fname: First name
  2. lname: Last name
  3. and email. 

Hidden Fields

Pay close attention to this code:

1
$output .='<input type="hidden" value="'.$list.'" name="list">';
2
$output .='<input type="hidden" name="action" value="et_mailchimp" />';
3
$output .= wp_nonce_field( "et_mailchimp_action", "et_mailchimp_nonce", false, false );

This is a very important part of the form; three crucial fields hidden from the user. 

  1. The first one is the list that the user will be subscribed to.
  2. The second one is the action that is required to handle the Mailchimp subscription functionality from the AJAX request. You can give any value to it, but remember it as we will need it in future. 
  3. And the last one is the nonce field that is used for validation. In other words this field value should be validated to make sure the request comes from our site.

And also take a closer look at the action and method attributes of the form:

1
action="'.esc_url( admin_url('admin-post.php') ).'"
2
method="POST"

Now if you go to Admin > Appearance > Widgets you will see our newly added widget. Add it to the widget area and you will see the subscribe form appear on the front-end!

Our newsletter subscribe form widgetOur newsletter subscribe form widgetOur newsletter subscribe form widget

Looking good! If you try to subscribe now nothing will happen as we haven’t yet created the AJAX and action handler yet. Let’s do that next.

Create AJAX POST and Action Handler

Open the JavaScript file we created earlier and paste the following (large amount of) code into it:

1
(function($){
2
3
    "use strict";
4
5
    var valid = "invalid";
6
    function validateValue($value, $target, $placeholder,$email){
7
        if ($email == true) {
8
            var n = $value.indexOf("@");
9
            var r = $value.lastIndexOf(".");
10
            if (n < 1 || r < n + 2 || r + 2 >= $value.length) {
11
                valid =  "invalid";
12
            } else {
13
                valid = "valid";
14
            }
15
            
16
            if ($value == null || $value == "" || valid == "invalid") {
17
                $target.addClass('visible');
18
            } else {
19
                $target.removeClass('visible');
20
            }
21
22
        } else {
23
            if ($value == null || $value == "" || $value == $placeholder) {
24
                $target.addClass('visible');
25
            } else {
26
                $target.removeClass('visible');
27
            }
28
        }
29
    };
30
31
    $('.et-mailchimp-form').each(function(){
32
33
        var $this = $(this);
34
35
        $this.submit(function(event) {
36
37
            // 1. Prevent form submit default

38
39
            event.preventDefault();
40
41
            // 2. serialize form data

42
43
            var formData = $this.serialize();
44
45
            var email   = $this.find("input[name='email']"),
46
                fname   = $this.find("input[name='fname']"),
47
                lname   = $this.find("input[name='lname']"),
48
                list    = $this.find("input[name='list']");
49
50
            // 3. Before submit validate email

51
52
            validateValue(email.val(), email.next(".alert"), email.attr('data-placeholder'), true);
53
54
            if (email.val() != email.attr('data-placeholder') && valid == "valid"){
55
56
                $this.find(".sending").addClass('visible');
57
58
                // 4. POST AJAX

59
60
                $.ajax({
61
                    type: 'POST',
62
                    url: $this.attr('action'),
63
                    data: formData
64
                })
65
                .done(function(response) {
66
67
                    // 5. If success show the success message to user

68
69
                    $this.find(".sending").removeClass('visible');
70
                    $this.find(".et-mailchimp-success").addClass('visible');
71
                    setTimeout(function(){
72
                        $this.find(".et-mailchimp-success").removeClass('visible');
73
                    },2000);
74
                })
75
                .fail(function(data) {
76
77
                    // 6. If fail show the error message to user

78
79
                    $this.find(".sending").removeClass('visible');
80
                    $this.find(".et-mailchimp-error").addClass('visible');
81
                    setTimeout(function(){
82
                        $this.find(".et-mailchimp-error").removeClass('visible');
83
                    },2000);
84
                })
85
                .always(function(){
86
87
                    // 7. Clear the form fields for next subscibe request

88
89
                    setTimeout(function(){
90
                        $this.find("input[name='email']").val(email.attr('data-placeholder'));
91
                        $this.find("input[name='fname']").val(fname.attr('data-placeholder'));
92
                        $this.find("input[name='lname']").val(lname.attr('data-placeholder'));
93
                    },2000);
94
                });
95
96
            }
97
        });
98
    });
99
100
})(jQuery);

This is an AJAX POST that sends our form data to the Mailchimp subscription action handler that we will write in a moment. I broke the process into seven steps which you’ll see annotated in the snippet. 

At the top of the file, up to line 29, you’ll find an email validation function. Let me explain each of the other steps here:

  1. First we will need to prevent default submit behavior of the form so that it remains on the page and handles the request with AJAX.
  2. Next we serialize the input data both from the user and from our hidden fields.
  3. Next, before the submission, we need to make sure the email is valid.
  4. After that we make a simple AJAX POST. Here we need three parameters, the request type: POST, the url – the form action attribute, and the data that is our serialized data.
  5. And if the request is successful we send the data to our action handler and show a success message to the user.
  6. If there was an error, we should inform the user.
  7. And always after a success or fail we clean the form fields for future entry.

Now if you go to the front-end and submit the form you will get the success message, but the subscription won’t actually take place as the subscribe action is not yet created. 

Create the Subscribe Action

And so, for the last part. Go to the plugin’s main file and at the very bottom add the code:

1
function mailchimp_action(){
2
3
    if ( ! isset( $_POST['et_mailchimp_nonce'] ) || !wp_verify_nonce( $_POST['et_mailchimp_nonce'], 'et_mailchimp_action' )) {
4
       exit;
5
    } else {
6
7
        $email     = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
8
        $fname     = strip_tags(trim($_POST["fname"]));
9
        $lname     = strip_tags(trim($_POST["lname"]));
10
        $list      = strip_tags(trim($_POST["list"]));
11
        $api_key   = MAILCHIMP_API;
12
13
        mailchimp_post($email, 'subscribed', $list, $api_key, array('FNAME' => $fname,'LNAME' => $lname) );
14
        
15
        die;
16
    }
17
}
18
add_action('admin_post_nopriv_et_mailchimp', 'mailchimp_action');
19
add_action('admin_post_et_mailchimp', 'mailchimp_action');

Important!

Notice the last two lines, which are as follows:

1
add_action('admin_post_nopriv_et_mailchimp', 'mailchimp_action');
2
add_action('admin_post_et_mailchimp', 'mailchimp_action');

The last part of the first parameters of our two actions is et_mailchimp –this is the hidden field value that we have in our form. By using these, WordPress understands that it needs to handle the specific form request. So if you used different naming for your hidden action field, make sure your actions are added correctly, like this:

1
add_action('admin_post_nopriv_{your_action_name}', 'your_action_function_name');
2
add_action('admin_post_{your_action_name}', ' your_action_function_name ');

Nonce

You’ll notice the first thing we did was to make sure the nonce field is valid and verified; only after that we will subscribe the user to the list. This is for security reasons., and you can read more about nonce in the WordPress codex.

After the nonce verification we can subscribe the user with a new function that we will build now: mailchimp_post(). It requires several parameters:

  • User email
  • Subscriber status
  • Targeted list
  • API key
  • And user data, i.e. first name and last name.

Just before the mailchimp_action() function add the following code:

1
function mailchimp_post( $email, $status, $list_id, $api_key, $merge_fields = array('FNAME' => '','LNAME' => '') ){
2
3
    $data = array(
4
        'apikey'        => $api_key,
5
        'email_address' => $email,
6
        'status'        => $status,
7
        'merge_fields'  => $merge_fields
8
    );
9
10
    $url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($data['email_address']));
11
12
    $headers = array(
13
        'Content-Type: application/json', 
14
    	'Authorization: Basic '.base64_encode( 'user:'.$api_key )
15
	);
16
17
    $$mailchimp = curl_init();
18
 
19
    curl_setopt($$mailchimp, CURLOPT_URL, $url);
20
    curl_setopt($$mailchimp, CURLOPT_HTTPHEADER, $headers);
21
    curl_setopt($$mailchimp, CURLOPT_RETURNTRANSFER, true); 
22
    curl_setopt($$mailchimp, CURLOPT_CUSTOMREQUEST, 'PUT');
23
    curl_setopt($$mailchimp, CURLOPT_TIMEOUT, 10);
24
    curl_setopt($$mailchimp, CURLOPT_POST, true);
25
    curl_setopt($$mailchimp, CURLOPT_POSTFIELDS, json_encode($data) );
26
    curl_setopt($$mailchimp, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
27
    curl_setopt($$mailchimp, CURLOPT_SSL_VERIFYPEER, false);
28
 
29
    return curl_exec($$mailchimp);
30
}

It’s very similar to the mailchimp_connect() function we wrote earlier, except it has a different request type, different url.

This function takes our user data and using the Mailchimp REST API it adds the user to the targeted list using the curl function.

Add Some Simple Styles

Now our widget is complete! We just need to add some subtle style changes. So open the style file we created earlier and paste the following style rules:

1
.widget_mailchimp form {
2
    margin:0;
3
	position: relative;
4
}
5
.widget_mailchimp form input {
6
	margin-top: 12px;
7
}
8
9
.widget_mailchimp .alert:not(.visible) {display: none;}
10
11
.widget_mailchimp .send-div {
12
	position: relative;
13
}
14
15
.widget_mailchimp .sending {
16
    position: absolute;
17
    bottom: 8px;
18
    right: 0;
19
    display: none;
20
	width: 32px;
21
	height: 32px;
22
}
23
24
.widget_mailchimp .sending.visible {display: block;}
25
26
.widget_mailchimp .sending:after {
27
	content: " ";
28
	display: block;
29
	width: 32px;
30
	height: 32px;
31
	margin: 1px;
32
	border-radius: 50%;
33
	border: 2px solid #c0c0c0;
34
	border-color: #c0c0c0 transparent #c0c0c0 transparent;
35
	animation: lds-dual-ring 0.5s linear infinite;
36
}
37
38
@keyframes lds-dual-ring {
39
	0% {
40
		transform: rotate(0deg);
41
	}
42
	100% {
43
		transform: rotate(360deg);
44
	}
45
}

Now, clear the browser cache and visit your site’s front-end to check everything is working perfectly. The subscription should work on live sties and locally running sites!

Conclusion

I hope you enjoyed this tutorial on creating a Mailchimp subscribe form widget for WordPress, using the Mailchimp API. It was quite a substantial one! Here is the link to the GitHub repo; you can download the plugin, modify it, and use it in any project you like!

Oo-oo-ooh! More Mailchimp Goodness

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.