Created
March 10, 2020 00:54
-
-
Save BruceMcKinnon/e8e69ca989467e62d5f620baa9756ade to your computer and use it in GitHub Desktop.
GForm Mailchimp validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'gform_field_validation', 'check_mailchimp_status', 10, 4 ); | |
function check_mailchimp_status ( $result, $value, $form, $field ) { | |
$target_form = 10; | |
if ( ($field->formId == $target_form) && ($field->id == 1) ) { | |
if ( $field->type == 'email' && $result['is_valid'] && class_exists( 'GF_MailChimp_API' ) ) { | |
fb_log( 'gform_field_validation: running.' ); | |
$api_key = gf_mailchimp()->get_plugin_setting( 'apiKey' ); | |
if ( rgblank( $api_key ) ) { | |
return $result; | |
} | |
$entry = GFFormsModel::get_current_lead(); | |
$feeds = gf_mailchimp()->get_single_submission_feed_by_form( $form, $entry ); | |
$list_id = $feeds['meta']['mailchimpList']; | |
if ( empty( $list_id ) ) { | |
return $result; | |
} | |
try { | |
// Get member info. | |
$mc_api = new GF_MailChimp_API( $api_key ); | |
$member = $mc_api->get_list_member( $list_id, $value ); | |
// Set member status. | |
$member_status = $member['status']; | |
} catch ( Exception $e ) { | |
// The email is not on the list or there was an API issue. | |
$member_status = false; | |
} | |
// | |
// Populate the Mailchimp member status field - ????????? | |
// | |
$form = rgpost( $member_status ); | |
if ( $member_status != 'subscribed' ) { | |
fb_log(print_r( $member_status, true ) ); | |
} | |
if ( $member_status == 'subscribed' ) { | |
$result['is_valid'] = true; | |
$result['message'] = ''; | |
} elseif ( $member_status == 'pending' ) { | |
$result['is_valid'] = false; | |
$result['message'] = empty( $field->errorMessage ) ? '<div class="large"><p>Please check your email for a confirmation email.</p><p>You must click the \'Yes, subscribe me to this list\' button to confirm your subscription.</p></div>' : $field->errorMessage; | |
} else { | |
$result['is_valid'] = false; | |
$result['message'] = empty( $field->errorMessage ) ? '<div class="large"><p>You must be signed up to and have confirmed your subscription to the CFO Newsletter to access this resource.</p><p><a href="'.get_bloginfo('url').'/sign-up-for-our-newsletter?returnPath='.get_current_page_slug().'#gf_10">Click here to sign up now</a>.</p></div>'.$extra_js : $field->errorMessage; | |
} | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment