Mailchimp WordPress Without Plugin

In this tutorial we will integrate Mailchimp to WordPress powered site without installing any plugin, take note that we will use Mailchimp API Version 3.0

• First get an API key on ‘/account/api/’

Mailchimp API Keys Section - mailchimp wordpress without plugin
Mailchimp API Keys Section

• Create a new list or audience on ‘/lists/’

Create New Audience - mailchimp wordpress without plugin
Create New Audience

• Get the list or audience ID

Audience Settings - mailchimp wordpress without plugin
Audience Settings
Audience List ID - mailchimp wordpress without plugin
Audience List ID

1. You can paste the following code on your functions.php, Now lets create a form with text and email field to shortcode:

/**
 * Mailchimp WordPress without plugin - shortcode
 */
function mailchimp_without_plugin_form( $atts ) {
    $a = shortcode_atts( array(
        'title_field' => 'Subscribe Now!',
        'invite_text' => 'We send our updates straight to your inbox',
        'button_text' => 'Subscribe',
        'list_id' => ''
    ), $atts );

    $title_field = $a['title_field'];
    $invite_text = $a['invite_text'];
    $button_text = $a['button_text'];
    $list_id = $a['list_id'];

    $form = "<div class=\"mailchimp-without-plugin__form-wrapper\">
                <form method=\"post\" class=\"mailchimp-without-plugin__mainform\" autocomplete=\"off\">
                    <h3 class=\"mailchimp-without-plugin__widget-title\">{$title_field}</h3>
                    <input type=\"email\" name=\"email\" required />
                    <button type=\"button\" id=\"mcwop-btn\" class=\"mailchimp-without-plugin__widget-button\">{$button_text}</button>
                    <p class=\"mailchimp-without-plugin__widget-blurb\">{$invite_text}</p>
                    <input type=\"hidden\" name=\"list_id\" value=\"{$list_id}\" />
                    <div id=\"mcwop-response-box\"></div>
                </form>
           </div>";

    return $form;
}
add_shortcode( 'mailchimp_without_plugin_form', 'mailchimp_without_plugin_form' );

2. Next we create a new widget that we could help us easily insert or edit value inside WordPress admin

/**
 * Mailchimp WordPress without plugin - widget main class
 */
class Mailchimp_Without_Plugin_Form_Basic_Widget extends WP_Widget {
    // Set up the widget name and description.
    public function __construct() {
      $widget_options = array( 'classname' => 'Mailchimp_Without_Plugin_Form_Basic_Widget', 'description' => 'Display basic Mailchimp subscribe form.' );
      parent::__construct( 'Mailchimp_Without_Plugin_Form_Basic_Widget', 'Mailchimp Custom - Basic', $widget_options );
    }
  
    // Create the widget output.
    public function widget( $args, $instance ) {
      echo do_shortcode('[mailchimp_without_plugin_form title_field="'.$instance['title_field'].'" invite_text="'.$instance['invite_text'].'" list_id="'.$instance['list_id'].'"]');
    }
  
    // Create the admin area widget settings form.
    public function form( $instance ) {
      global $wp_customize;
      $title_field = ! empty( $instance['title_field'] ) ? $instance['title_field'] : '';
      $invite_text = ! empty( $instance['invite_text'] ) ? $instance['invite_text'] : '';
      $list_id = ! empty( $instance['list_id'] ) ? $instance['list_id'] : ''; ?>
      <p>
        <label for="<?php echo $this->get_field_id( 'title_field' ); ?>"><?php _e( 'Title:', 'mcwop' ) ?></label>
        <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title_field' ); ?>" name="<?php echo $this->get_field_name( 'title_field' ); ?>" value="<?php echo $title_field; ?>"/>
      </p>
      <p>
        <label for="<?php echo $this->get_field_id( 'invite_text' ); ?>"><?php _e( 'Invite Text:', 'mcwop' ) ?></label>
        <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'invite_text' ); ?>" name="<?php echo $this->get_field_name( 'invite_text' ); ?>" value="<?php echo $invite_text; ?>"/>
      </p>
      <p>
        <label for="<?php echo $this->get_field_id( 'list_id' ); ?>"><?php _e( 'List ID:', 'mcwop' ) ?></label>
        <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'list_id' ); ?>" name="<?php echo $this->get_field_name( 'list_id' ); ?>" value="<?php echo $list_id; ?>"/>
      </p><?php
    }
  
    // Apply settings to the widget instance.
    public function update( $new_instance, $old_instance ) {
      $instance = $old_instance;
      $instance['title_field'] = $new_instance['title_field'];
      $instance['invite_text'] = $new_instance['invite_text'];
      $instance['list_id'] = $new_instance['list_id'];
      return $instance;
    }
}

/**
 * Mailchimp WordPress without plugin - register widget
 */
function Mailchimp_Without_Plugin_Form_Basic_Widget_Register() {
  register_widget( 'Mailchimp_Without_Plugin_Form_Basic_Widget' );
}
add_action( 'widgets_init', 'Mailchimp_Without_Plugin_Form_Basic_Widget_Register' );

3. Since we would like this mini snippet works without any page refresh when your visitors submit their email, we need to create an ajax handler and register our Mailchimp form assets to style it.

Note: You need Mailchimp API key to make this code work

/**
 * Mailchimp WordPress without plugin - ajax handler
 */
function mailchimp_without_plugin_submission() {
    // set variables and response.
    $response = array();
    $email = $_POST['email'];
    $list_id = $_POST['list_id'];
    $api_key = 'Insert Your Mailchimp API Key Here';

    if ( empty( $email ) || filter_var( $email, FILTER_VALIDATE_EMAIL ) === false ) {
        $response['message'] = '<p class="mcwop-alert-danger">Please enter valid email address.</p>';
        echo json_encode( $response );
        exit;
    }
    
    $member_id = md5( strtolower( $email ) );
    $mailchimp_server = substr( $api_key, strpos( $api_key, '-' ) + 1 );
    $url = 'https://' . $mailchimp_server . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . $member_id;
        
    $json = json_encode([
        'email_address' => $email,
        'status'        => 'subscribed'
    ]);
        
    // send a HTTP POST request with curl
    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_USERPWD, 'user:' . $api_key );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json'] );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
    curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
    $result = curl_exec( $ch );
    $httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
    curl_close( $ch );
        
    if ( $httpCode == 200 ) {
        $response['status'] = 200;
        $response['message'] = '<p class="mcwop-alert-success">You have successfully subscribed!</p>';
    } else {
        switch ( $httpCode ) {
            case 214:
                $mailchimp_error_message = 'You are already subscribed.';
                break;
            
            default:
                $mailchimp_error_message = 'Some problem occurred, please try again.';
                break;
        }
        $response['message'] = '<p class="mcwop-alert-warning">' . $mailchimp_error_message . '</p>';
    }

    echo json_encode( $response );
    exit;
}
add_action( 'wp_ajax_mailchimp_without_plugin_submission', 'mailchimp_without_plugin_submission' );
add_action( 'wp_ajax_nopriv_mailchimp_without_plugin_submission', 'mailchimp_without_plugin_submission' );

/**
 * Mailchimp WordPress without plugin - js and css
 */
function mailchimp_without_plugin_assets() {
    wp_enqueue_style( 'mcwop-css', get_stylesheet_directory_uri() . '/mcwop/mailchimp-custom.css' );
    wp_register_script( 'mcwop-javascript', get_stylesheet_directory_uri() . '/mcwop/mailchimp-custom.js', array( 'jquery' ) );
    wp_localize_script( 'mcwop-javascript', 'mcwop_form_submission_params', array( 'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php' ) );
    wp_enqueue_script( 'mcwop-javascript' );
}
add_action( 'wp_enqueue_scripts', 'mailchimp_without_plugin_assets' );

* Create folder name ‘mcwop’ inside your current theme folder, then insert two files:
mailchimp-custom.css

/* Mailchimp WordPress without plugin - main css */
.mailchimp-without-plugin__form-wrapper {
    margin-bottom: 40px;
}

#mcwop-btn {
    border: 1px solid #fff852;
    background: #fff852;
    height: 31px;
    padding: 0 10px;
    line-height: 1;
}

.mcwop-alert-danger,
.mcwop-alert-success,
.mcwop-alert-warning {
    font-size: 13px;
    margin-top: 10px;
}

.mcwop-alert-danger {
    color: #ff0000;
}

.mcwop-alert-warning {
    color: #ffa500;
}

.mcwop-alert-success {
    color: #007f00;
}

.mailchimp-without-plugin__mainform input[type="email"] {
    padding-left: 10px;
    padding-right: 10px;
    box-sizing: border-box;
    max-width: 160px;
}

.mailchimp-without-plugin__widget-blurb {
    margin-top: 10px;
    font-size: 13px;
}

mailchimp-custom.js

/* Mailchimp WordPress without plugin - main javascript */
jQuery(document).ready(function(){
    jQuery('#mcwop-btn').on('click', function(e){
        e.preventDefault();
        var button = jQuery(this);
        var dataPosts = {
                'action' : 'mailchimp_without_plugin_submission',
                'email' : jQuery('.mailchimp-without-plugin__mainform input[name="email"]').val(),
                'list_id' : jQuery('.mailchimp-without-plugin__mainform input[name="list_id"]').val()
            };

        jQuery.ajax({
            url : mcwop_form_submission_params.ajaxurl,
            data : dataPosts,
            dataType: "text",
            type : 'POST',
            beforeSend : function () {
                button.text('Processing').attr('disabled');
                jQuery('#mcwop-response-box').text('');
            },
            success : function(data){
                var json = jQuery.parseJSON(data);
                jQuery('#mcwop-response-box').append(json.message);
                jQuery('.mailchimp-without-plugin__mainform input[name="email"]').val('');
                button.text('Subscribe').removeAttr('disabled');
            }
        });
    });
});

Now you have successfully integrate Mailchimp on your WordPress website without any plugin via shortcode or widget.


Sample shortcode usage:

[mailchimp_without_plugin_form title_field="Subscribe Here" invite_text="Once you subscribe, we deliver our updates to your inbox." list_id="Your_Mailchimp_ListID_Here"]

For widget, see it on WordPress backend inside Widget Area name ‘Mailchimp Custom – Basic’

1 thought on “Mailchimp WordPress Without Plugin”

Leave a Reply

Your email address will not be published. Required fields are marked *

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