Create and Send a MailChimp Campaign With MailChimp API v3.0 in WordPress

This is how you can create and send a MailChimp campaign using the MailChimp API version 3.0 in WordPress.

(If you want to get a list of all existing MailChimp campaigns, see this, instead.)

The first function is a generic function to make any type of request to the MailChimp API v3.

The second function is used to specifically create a MailChimp campaign with the MailChimp API version 3. You would use it like this to create a campaign:

$campaign_id = isa_create_mailchimp_campaign( $list_id, $subject );

The $list_id would be your MailChimp audience ID that you want to send this campaign to. The $subject is the email subject line for this campaign. This function, isa_create_mailchimp_campaign, will return the campaign ID if it was successfully created, otherwise it will return false. (See the Usage Example below.)

Then, you would use the campaign ID to assign a template and set the HTML content for this campaign. That’s what the third function is for (isa_set_mail_campaign_content).

These first 3 functions simply go into your functions file. These 3 functions simply provide an API to be able to create, edit, and send MailChimp campaigns through WordPress, using the MailChimp API v3. After adding these functions, see the Usage Example, below.

The lines you have to edit here are:

  • line 15: Replace YOUR_API_KEY with your own MailChimp API key.
  • line 56: Replace “Your Company Email Address” with your desired “reply to” email address.
  • line 57: Replace “Your Company Name” with your desired “from name.”
/**
 * Make a request to MailChimp API v3
 *
 * @param string $endpoint The MailChimp API endpoint for this request WITHOUT starting slash
 * @param string $type Type of request, whether GET, POST, PATCH, PUT, or DELETE
 * @param array $body The request body parameters
 *
 * @return $response object The response object
 * 
 */
function isa_mailchimp_api_request( $endpoint, $type = 'POST', $body = '' ) {

	// Configure --------------------------------------

	$api_key = 'YOUR_API_KEY';

	// STOP Configuring -------------------------------

	$core_api_endpoint = 'https://<dc>.api.mailchimp.com/3.0/';
	list(, $datacenter) = explode( '-', $api_key );
	$core_api_endpoint = str_replace( '<dc>', $datacenter, $core_api_endpoint );

	$url = $core_api_endpoint . $endpoint;

	$request_args = array(
		'method'      => $type,
		'timeout'     => 20,
		'headers'     => array(
			'Content-Type' => 'application/json',
			'Authorization' => 'apikey ' . $api_key
		)
	);

	if ( $body ) {
		$request_args['body'] = json_encode( $body );
	}

	$request = wp_remote_post( $url, $request_args );
	$response = is_wp_error( $request ) ? false : json_decode( wp_remote_retrieve_body( $request ) );

	return $response;
}

/**
 * Create a MailChimp campaign with MailChimp API v3
 *
 * @param $list_id string Your audience ID for this campaign
 * @param $subject string The email subject line for this campaign
 * @return mixed The campaign ID if it was successfully created, otherwise false.
 */

function isa_create_mailchimp_campaign( $list_id, $subject ) {

	// Configure --------------------------------------

	$reply_to	= 'Your Company Email Address';
	$from_name	= 'Your Company Name';

	// STOP Configuring -------------------------------

	$campaign_id = '';

	$body = array(
		'recipients'	=> array('list_id' => $list_id),
		'type'			=> 'regular',
		'settings'		=> array('subject_line' => $subject,
								'reply_to'		=> $reply_to,
								'from_name'		=> $from_name
								)
	);

	$create_campaign = isa_mailchimp_api_request( 'campaigns', 'POST', $body );

	if ( $create_campaign ) {
		if ( ! empty( $create_campaign->id ) && isset( $create_campaign->status ) && 'save' == $create_campaign->status ) {
			// The campaign id: 
			$campaign_id = $create_campaign->id;
		}
	}

	return $campaign_id ? $campaign_id : false;

}

/**
 * Set the HTML content for MailChimp campaign, given template sections, with MailChimp API v3
 *
 * @param $campaign_id string The Campaign ID
 * @param $template_content array Template Content including the Template ID and Sections
 * 
 * @return bool True if the content was set, otherwise false.
 */

function isa_set_mail_campaign_content( $campaign_id, $template_content ) {
	$set_content = '';
	$set_campaign_content = isa_mailchimp_api_request( "campaigns/$campaign_id/content", 'PUT', $template_content );

	if ( $set_campaign_content ) {
		if ( ! empty( $set_campaign_content->html ) ) {
			$set_content = true;
		}
	}
	return $set_content ? true : false;
}


Usage Example: Create a MailChimp Campaign, Set The Content, and Send The Campaign

This example will show you how to use the 3 functions (from above) to create a MailChimp campaign, and then set the content for that campaign, and then send the campaign. Note that this will send the campaign, immediately. (If you don’t want to send the campaign, comment out lines 37–51.)

The lines to edit in this section are:

  • line 7: Replace $list_id with your own MailChimp audience ID to send this campaign to. (I recommend that, for testing purposes, you first use an audience ID that has only your own test email address in it, so that you can test this and the email campaign will only be sent to you.)
  • line 7: Replace $subject with the email subject line for this campaign.
  • line 18: Replace 99999 with your own Template ID that you are going to use for this campaign. This should be a “Code your own” template that you created in MailChimp. A “Code your own” template will have the “mc:edit area” which is required so that you can set the content through the MailChimp API.
  • line 24: Replace std_content00 with the unique mc:edit area name for the body content area of your template.
  • line 24: Replace “THIS IS THE CONTENT OF MY EMAIL MESSAGE.” with your desired content for the body of the email message. This can include HTML.
/************************************************************
*
*  Create a MailChimp campaign, set the content, and SEND the campaign
*
************************************************************/

$campaign_id = isa_create_mailchimp_campaign( $list_id, $subject );

if ( $campaign_id ) {

	// Set the content for this campaign

	$template_content = array(

		'template' => array(

				// The id of the template to use. 
				'id' => 99999, // INTEGER

				// Content for the sections of the template. Each key should be the unique mc:edit area name from the template. 

				'sections'	=> array(
					
					'std_content00' => 'THIS IS THE CONTENT BODY OF MY EMAIL MESSAGE.'

			)

		)
	);

	$set_campaign_content = isa_set_mail_campaign_content( $campaign_id, $template_content );

	// Send the Campaign if the content was set.

	// NOTE: Campaign will send immediately.

	if ( $set_campaign_content ) {

		$send_campaign = isa_mailchimp_api_request( "campaigns/$campaign_id/actions/send", 'POST' );

		if ( empty( $send_campaign ) ) {

			// Campaign was sent!

		} elseif( isset( $send_campaign->detail ) ) {

			$error_detail = $send_campaign->detail;

		}

	}

}

See more:

We've 7 Responses

  1. September 2nd, 2017 at 1:44 pm

    Hello Isa,

    Whoa! Thanks for this cool example!
    I’ve been searching for something like this for ages.

    I’ver encountered an issue with the timeout value line 27 – nothing has been send.
    Increasing the value finally did the trick.

    functions.php

        $request_args = array(
            'method'      => $type,
            'timeout'     => 200,
            'headers'     => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'apikey ' . $api_key
            )
        );
    

    Even though this is quite obvious:
    For guys using blocked hosts in wp-config.php

    Its mandatory to add mailchimp.com to the list of accessible hosts.

    wp-config.php

    define( 'WP_HTTP_BLOCK_EXTERNAL', true );
    define( 'WP_ACCESSIBLE_HOSTS', 'api.wordpress.org, downloads.wordpress.org, *.github.com, api.google.com, *.google.com, *.mailchimp.com' );
    

    I guess there is no way to populate repeatable mc:edit elements via API?

    Maybe this is helpfull for somebody.

    Thanks a lot!
    Patrick

    Patrick
  2. September 15th, 2017 at 3:25 am

    I am following errors while sending emails

    stdClass Object
    (
        [type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
        [title] => Bad Request
        [status] => 400
        [detail] => Your Campaign is not ready to send.
        [instance] => 61202ca0-abe5-4635-912c-46d3325dd39a
    )
    

    Campaign is created but it it stays in status draft. plz propose a solution

    Sajid
  3. November 10th, 2017 at 1:39 pm

    Thank you SO much for this, Isa! Such a huge help. A few notes that may help someone else:
    – The $list_id isn’t what you see in the URL, and it must be a string. Find it here: https://kb.mailchimp.com/lists/manage-contacts/find-your-list-id
    – If a campaign doesn’t send, it might be an issue within Mailchimp. Go to edit the created campaign and see if there are any notes in the “Confrim” section (was default text or from address not validated for me)
    – To debug, add a print_r to show what the functions are returning – there will be errors in there.

    Lara Schenck
  4. February 6th, 2019 at 11:04 am

    Hi great article !!

    This sends the email to everyone on the list though.

    How can I programmatically send it to only one person on that email list?

    JJ Roberts
    • March 15th, 2019 at 3:54 pm

      To segment the recipients from your mailing list, edit the $body array in the “isa_create_mailchimp_campaign” function, this way:

      $body = array(
          'recipients' => array(
              'list_id' => $list_id,
              'segment_opts' => array(
                  'match' => 'all',
                  'conditions' => array(
                      array(
                          'condition_type' => 'EmailAddress',
                          'field' => 'EMAIL',
                          'op' => 'is',
                          'value' => $email_address,
                      ),
                  ),
              ),
          ),
          'type' => 'regular',
          'settings' => array('subject_line' => $subject,
              'reply_to' => $reply_to,
              'from_name' => $from_name,
          ),
      );
      

      Documentation (search for “recipients”):
      https://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/

      Thiago Santos
  5. May 1st, 2019 at 11:44 am

    Any alternative to using wp_remote_post for non-wordpress? I have tried a couple API classes, they just do not work. Would like to try this one, but non wordpress. Tried using using file_get_contents with stream_context_create. But stream_context_create giving me issues as well. Thanks.

    Shawn Rebelo

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]