0

Requirements:

  1. When a new post is created, a new mailing list is created in Mailchimp
  2. When the new mailing list is created in Mailchimp, the list ID is stored in the post's metadata
  3. When the post is viewed, the unique mailing list ID is used to create a mailing list subscription form on the page

Questions:

  1. What's the best WP hook to use to run the function every time a new post is created, and ONLY when it is created (not updated)? (This Stack Overflow post recommends the transition_post_status hook.)
  2. The Mailchimp API is used to create new mailing lists. Is there an open-source wrapper class it?
  3. What's the best way to store the unique mailing list list ID so that it is stored in the post's metadata? add_post_meta()?
Dirk Diggler
  • 863
  • 1
  • 10
  • 22

1 Answers1

0

My solution, using DrewM's Mailchimp API wrapper:

<?php
use \DrewM\MailChimp\MailChimp;
function so_48291110_new_mailchimp_list_on_publish( $new_status, $old_status, $post ) {
    // The first time our new post is published
    if ( $new_status == 'publish' && $old_status != 'publish' ) {
        // Mailchimp API instance
        $MailChimp = new MailChimp('My Mailchimip API Key');
        // Mailchimp Mailing List info
        $mailchimp_new_list_data = array(
            "name"             => "Mailing list for {$post->post_title}",
            "contact"          => array(
                "company" => "My company",
                /* ... */
            ),
            "campaign_defaults" => array(
                "from_name" => "My name",
                /* ... */
            ),
            /* ... */
        );
        // Create new mailing list
        $mailchimp_result = $MailChimp->post("lists", $mailchimp_new_list_data);
        // Store mailing list ID as metadata
        add_post_meta(
            get_the_id(),            // post ID
            'mailchimp_list_id',     // meta key
            $mailchimp_result["id"], // meta value
            true                     // unique
        );
    }
}

// Add action
add_action('transition_post_status', 'so_48291110_new_mailchimp_list_on_publish', 10, 3);
Dirk Diggler
  • 863
  • 1
  • 10
  • 22