Last active
May 24, 2024 13:29
-
-
Save nickkraakman/0c353c161715a38cb808a14abfc24313 to your computer and use it in GitHub Desktop.
Subscribe to- or remove users from MailPoet lists using the MailPoet API
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
// Subscribe to or remove from MailPoet | |
// Add this at the bottom of your WordPress theme's functions.php file | |
// POST to https://headjack.io/wp-admin/admin-post.php?action=subscribe_to_mailpoet | |
function subscribe_to_mailpoet() { | |
$api_key = "XXXXXXXXXX"; // Basic API key authentication, send over SSL | |
if ( !empty($_POST['key']) && $_POST['key'] == $api_key ) { | |
$subscriber_data = array( | |
'email' => sanitize_text_field($_POST['email']), | |
'first_name' => sanitize_text_field($_POST['first_name']), | |
'last_name' => sanitize_text_field($_POST['last_name']) | |
); | |
$options = array( | |
'send_confirmation_email' => false // default: true | |
//'schedule_welcome_email' => false | |
); | |
$default_list_id = array(11); | |
// Check if subscriber exists | |
try { | |
$subscriber = \MailPoet\API\API::MP('v1')->getSubscriber($subscriber_data['email']); | |
} catch(Exception $exception) { | |
// Subscriber does not yet exist, try to add subscriber | |
try { | |
$subscriber = \MailPoet\API\API::MP('v1')->addSubscriber($subscriber_data, $default_list_id); // Add to default mailing list | |
} catch(Exception $exception) { | |
echo json_encode($exception->getMessage()); | |
} | |
} | |
// Subscriber exists and needs to be added to certain lists | |
if (!empty($_POST["add_to_lists"])) { | |
$add_to_lists = array_map('intval', $_POST['add_to_lists']); | |
try { | |
$subscriber = \MailPoet\API\API::MP('v1')->subscribeToLists($subscriber_data['email'], $add_to_lists, $options); | |
} catch(Exception $exception) { | |
echo json_encode($exception->getMessage()); | |
} | |
} | |
// Subscriber exists and needs to be removed from certain lists | |
if (!empty($_POST["remove_from_lists"])) { | |
$remove_from_lists = array_map('intval', $_POST['remove_from_lists']); | |
try { | |
$subscriber = \MailPoet\API\API::MP('v1')->unsubscribeFromLists($subscriber_data['email'], $remove_from_lists, $options); | |
} catch(Exception $exception) { | |
echo json_encode($exception->getMessage()); | |
} | |
} | |
} | |
} | |
add_action('admin_post_subscribe_to_mailpoet', 'subscribe_to_mailpoet'); | |
add_action('admin_post_nopriv_subscribe_to_mailpoet', 'subscribe_to_mailpoet'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could not find API Key (on line 8) on Mailpoet.
Any possible advices? Thanks in advance!!