How to Add a User to Mailchimp After a Form Submission

Add a user to Mailchimp after a form submission

A common requirement on marketing sites is to automatically subscribe a user to a Mailchimp list when they submit a contact or registration form. Mailchimp provides a straightforward API endpoint for this, and WordPress makes it easy to call it with the HTTP API.

Problem: After a visitor submits a form on your WordPress site, you want to add them to a Mailchimp audience automatically, without installing a full Mailchimp integration plugin.

Solution: Use the Mailchimp Marketing API v3. Send a PUT request to the /lists/{list_id}/members/{subscriber_hash} endpoint with wp_remote_request(), where the subscriber hash is the MD5 hash of the lowercase email. PUT means “add or update”: it works for new subscribers and for people who are already on the list, while a POST to /members fails with “Member Exists” for them.

Step 1. Store the API key in wp-config.php

Keep your credentials out of the theme or plugin, which might end up in version control. Add them to wp-config.php:

define( 'MAILCHIMP_API_KEY', 'your-api-key-us6' );
define( 'MAILCHIMP_LIST_ID', 'your-list-id' );

The part of the key after the dash (us6 here) is the data center, and it is part of the API URL.

Step 2. Subscribe function

function subscribe_to_mailchimp( $email, $first_name = '', $last_name = '' ) {
    $email = sanitize_email( $email );

    if ( ! is_email( $email ) || ! defined( 'MAILCHIMP_API_KEY' ) ) {
        return false;
    }

    $api_key = MAILCHIMP_API_KEY;
    $dc      = substr( $api_key, strpos( $api_key, '-' ) + 1 ); // e.g. 'us6'
    $hash    = md5( strtolower( $email ) );
    $url     = "https://{$dc}.api.mailchimp.com/3.0/lists/" . MAILCHIMP_LIST_ID . "/members/{$hash}";

    $response = wp_remote_request( $url, [
        'method'  => 'PUT',
        'timeout' => 15,
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode( 'anystring:' . $api_key ),
            'Content-Type'  => 'application/json',
        ],
        'body'    => wp_json_encode( [
            'email_address' => $email,
            'status_if_new' => 'subscribed', // or 'pending' for double opt-in
            'merge_fields'  => [
                'FNAME' => sanitize_text_field( $first_name ),
                'LNAME' => sanitize_text_field( $last_name ),
            ],
        ] ),
    ] );

    if ( is_wp_error( $response ) ) {
        return false;
    }

    return 200 === wp_remote_retrieve_response_code( $response );
}

status_if_new sets the status only for new subscribers. People who unsubscribed earlier are not silently re-subscribed by a new form submission.

Step 3. Hook it into Contact Form 7

add_action( 'wpcf7_mail_sent', 'cf7_subscribe_to_mailchimp' );
function cf7_subscribe_to_mailchimp( $contact_form ) {
    $submission = WPCF7_Submission::get_instance();

    if ( ! $submission ) {
        return;
    }

    $data = $submission->get_posted_data();

    subscribe_to_mailchimp(
        $data['your-email']      ?? '',
        $data['your-first-name'] ?? '',
        $data['your-last-name']  ?? ''
    );
}

Replace your-email, your-first-name and your-last-name with the field names from your form. To subscribe only visitors who agreed to it, add an acceptance checkbox to the form and check its value before calling the function.

NOTE: Use 'pending' instead of 'subscribed' if your audience requires double opt-in, for example to comply with GDPR. Mailchimp then sends a confirmation email, and the person is added only after confirming.

Sources:

  1. https://mailchimp.com/developer/marketing/api/list-members/add-or-update-list-member/