Developer Diaries: Comments and Mailchimp

Laptop computer displaying logo of Mailchimp, an American marketing automation platform and email marketing service
License: Adobe Stock Editorial

As detailed in my previous developer diary entry, I decided on three new features for Comment Edit Pro: Akismet, Mailchimp, and reCaptcha integration.

reCaptcha has already been covered in my post about enabling reCaptcha on a comment form.

Today I want to concentrate on the Mailchimp integration.

Why Mailchimp?

Mailchimp is by far the largest provider for newsletters. So assuming your plugin needs a newsletter add-on, you’ll want to start with Mailchimp.

Screenshot of www.emailtooltester.com

A breakdown of how Mailchimp has a large market share

So with that out of the way, let’s go into the meat of the feature.

Leave a comment and subscribe

I had the idea of allowing some sort of newsletter opt-in as a user was leaving a comment. They’d check a box when leaving a comment, and boom, they’re subscribed.

For those with a lot of commenters, they might find that a Mailchimp integration would be a great way to get more subscribers.

Mailchimp Sign-up Checkbox for the comment form
Mailchimp Sign-up Checkbox for the comment form

In technical terms, I imagined a checkbox and a label between the comment form and the submit button. Once the comment is submitted, behind the scenes, we send a request to the newsletter API and add the subscriber to a list. Simple, yeah?

The Mailchimp API

Screenshot of mailchimp.com

Mailchimp API – Connecting to the API

Luckily for me, integrating with Mailchimp is as easy as requiring the Mailchimp API key. Yes, they have OAuth, but I thought this was overkill for a comment section integration.

Mailchimp Extra API Key
Mailchimp Extras API Key

To get a Mailchimp API key, you would go to your Mailchimp profile and click on the Extras->API menu item.

Mailchimp API Key Screen
Mailchimp API Key Screen

Once I had my API key, I could begin with the Mailchimp integration.

Mailchimp admin settings

As I began integrating Mailchimp into my admin settings, I mapped out several requirements.

Enabling Mailchimp

First, there’s a toggle to enable Mailchimp.

Mailchimp Toggle Switch
Mailchimp Toggle Switch

Entering the API key

Once Mailchimp is enabled, it prompts for your API key.

Mailchimp API Prompt
Mailchimp API Prompt

The Mailchimp server prefix

Once the user enters their Mailchimp API key, a server prefix is automatically generated, and you can save the Mailchimp options.

Since the Mailchimp integration is coded in React, I just used a simple RegEx to get the server prefix. I needed the server prefix in order to communicate with Mailchimp’s API. Rather than have the user enter this, I automatically generated this since the last few characters in the API key are the server prefix.

useEffect( () => {
	const apiKey = getValues( 'apiKey' );
	if ( '' === apiKey || null === apiKey ) {
		return;
	}
	// Try to get server prefix for Mailchimp API key.
	const regex = new RegExp( /-(\w+)$/ );
	const matches = apiKey.match( regex );

	// If no matches, return empty string.
	if ( null === matches ) {
		return;
	}

	// We have matches! Match should be index 1.
	const serverPrefix = matches[ 1 ];

	setValue( 'mailchimpServerPrefix', serverPrefix, {
		shouldDirty: false,
		shouldValidate: false,
		shouldTouch: false,
	} );
}, [ formValues.apiKey ] );
Code language: JavaScript (javascript)
Mailchimp Server Prefix
Mailchimp Server Prefix

Getting the Mailchimp lists

Once the API key is entered and a user saves the form, you are served with radio options to select a default list.

Selecting a Mailchimp List
Selecting a Mailchimp List

Behind the scenes, I’m communicating with the Mailchimp API endpoint, which I declare as a class variable:

/**
 * Mailchimp API variable with <sp> (server prefix) for search/replace.
 *
 * @var string Mailchimp API variable.
 */
private $mailchimp_api = 'https://<sp>.api.mailchimp.com/3.0/';Code language: PHP (php)

There’s a <sp> prefix, and I replace that with the actual server prefix.

// Format API url for a server prefix..
$mailchimp_api_url = str_replace(
	'<sp>',
	$api_server_prefix,
	$this->mailchimp_api
);Code language: PHP (php)

Finally, I perform the API request and return any found lists.

// Start building up HTTP args.
$http_args            = array();
$http_args['headers'] = array(
	'Authorization' => 'Bearer ' . $api_token,
	'Accept'        => 'application/json;ver=1.0',
);

// Get lists endpoint.
$lists_api_url = esc_url_raw( $mailchimp_api_url . '/lists' );

// Make API call.
$response = wp_remote_get( $lists_api_url, $http_args );Code language: PHP (php)

Setting the Mailchimp label

After a user has selected a list, you can now modify the label that is shown in the comment section. You can also modify whether the sign-up prompt is checked by default or not.

Setting the Subscribe Label

Adding Mailchimp to the comments section

Mailchimp Signup Label
Mailchimp Signup Label

To place the signup checkbox above the submit button, I used the following filter: comment_form_defaults.

// Add Mailchimp Checkbox.
add_filter( 'comment_form_defaults', array( $this, 'add_mailchimp_checkbox' ), 100 );Code language: PHP (php)

Here’s the callback code I use to add the checkbox.

/**
 * Add an nakcguno option below the comment textarea and above the submit button.
 *
 * @param array $comment_fields Array of defaults for the form field.
 */
public function add_mailchimp_checkbox( $comment_fields ) {
	$options           = Options::get_options();
	$mailchimp_enabled = (bool) $options['enable_mailchimp'];

	// Chceck to see if Mailchimp is enabled.
	if ( ! $mailchimp_enabled || current_user_can( 'moderate_comments' ) ) {
		return $comment_fields;
	}

	// Now get the checkbox details.
	$checked_by_default              = (bool) $options['mailchimp_checkbox_enabled'];
	$mailchimp_html                  = array(
		'sce-mailchimp' => sprintf(
			'<section class="comment-form-sce-mailchimp"><label><input type="checkbox" name="sce-mailchimp-signup" %s /> %s</label></section>',
			checked( $checked_by_default, true, false ),
			esc_html( $options['mailchimp_signup_label'] )
		),
	);
	$comment_fields['submit_button'] = $mailchimp_html['sce-mailchimp'] . $comment_fields['submit_button'];
	return $comment_fields;
}Code language: PHP (php)

Capturing the subscriber

If the user checks the subscribe checkbox, I use the following action to grab it: comment_post

// When a new comment has been added.
add_action( 'comment_post', array( $this, 'comment_posted' ), 100, 2 );Code language: PHP (php)

If all checks out, I add the subscriber:

/**
 * Send Mailchimp when a comment has been posted.
 *
 * @param int  $comment_id Comment ID that has been submitted.
 * @param bool $maybe_comment_approved Whether the comment is approved or not (1, 0, spam).
 */
public function comment_posted( $comment_id, $maybe_comment_approved ) {
	$signup_enabled = (bool) filter_input( INPUT_POST, 'sce-mailchimp-signup', FILTER_VALIDATE_BOOLEAN );

	if ( $signup_enabled && 'spam' !== $maybe_comment_approved ) {
		// Get the comment.
		$comment         = get_comment( $comment_id );
		$commenter_email = $comment->comment_author_email;

		$subscriber_added = $this->add_subscriber( $comment_id, $commenter_email, $comment );
	}
}Code language: PHP (php)

And here’s a small snippet where I create the new subscriber:

$http_args            = array();
$http_args['headers'] = array(
	'Authorization' => 'Bearer ' . $mailchimp_api_key,
	'Accept'        => 'application/json;ver=1.0',
);
$http_args['body']    = wp_json_encode(
	array(
		'email_address' => $email,
		'status'        => 'pending',
		'merge_fields'  => array(
			'FNAME' => $commenter_name,
		),
	)
);
$response             = wp_remote_post( esc_url_raw( $endpoint ), $http_args );Code language: PHP (php)

Conclusion

The Mailchimp feature will soon be released in Comment Edits Pro.

Integrating Mailchimp was fairly straightforward, and I think it’ll be a solid addition to the comment section.

Ronald Huereca
Ronald Huereca

Ronald Huereca

Ronald has been part of the WordPress community since 2006, starting off writing and eventually diving into WordPress plugin development and writing tutorials and opinionated pieces.

No stranger to controversy and opinionated takes on tough topics, Ronald writes honestly when he covers a topic.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Ronald Huereca
MediaRon - Ronald Huereca

Ronald created MediaRon in 2011 and has more than fifteen years of releasing free and paid WordPress plugins.

Quick Links

Say Hi