Skip to content

Instantly share code, notes, and snippets.

@n8kowald
Last active August 10, 2018 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8kowald/a6e4dcdf19db2c7d078cec7dc16a4f89 to your computer and use it in GitHub Desktop.
Save n8kowald/a6e4dcdf19db2c7d078cec7dc16a4f89 to your computer and use it in GitHub Desktop.
"Email Subscribers & Newsletters" WordPress Plugin - Add ability to subscribe/unsubscribe from backend
<?php
/* Email Subscribers & Newsletters - by Icegram (https://wordpress.org/plugins/email-subscribers)
These functions allow you to subscribe/unsubscribe a user to an email group without using a signup form. */
/**
* Subscribe a user to a given newsletter group
*
* @param $user_id
* @param $group
* @throws Exception
* @return bool
*/
function subscribe_user_to_email_notifications( $user_id, $group ) {
if ( empty( $group ) ) {
throw new InvalidArgumentException( 'Email group is required' );
}
$user = get_userdata( $user_id );
if ( !$user ) {
throw new Exception( 'User not found' . $user_id );
}
$data = array();
$data['es_form_submit'] = 'yes';
$data['es_nonce'] = wp_create_nonce( 'es-subscribe' );
$data['es_email_mail'] = $user->user_email;
$data['es_email_name'] = $user->first_name;
$data['es_email_group'] = $group;
$data['es_email_status'] = 'Confirmed';
$result = es_cls_dbquery::es_view_subscriber_ins( $data );
if ($result === 'ext') {
throw new Exception('Subscription already exists for ' . $user->user_email . ' in the ' . $group . ' group');
}
if ($result === 'invalid') {
throw new Exception('Invalid email address: ' . $user->user_email );
}
// Successful subscription
if ($result === 'sus') {
return true;
}
}
/**
* Get a subscriber record from the database that matches the user and group
*
* @param $user_id
* @param $group
* @throws Exception
* @return array|null|object
*/
function get_subscriber( $user_id, $group ) {
if ( empty( $group ) ) {
throw new InvalidArgumentException( 'Email group is required' );
}
$user = get_userdata($user_id);
if (!$user) {
throw new Exception('Invalid user ID');
}
$subscriber = es_cls_dbquery::es_view_subscriber_one($user->user_email, $group);
if (empty($subscriber[0])) {
throw new Exception('No subscriber found');
}
return $subscriber;
}
/**
* Unsubscribe a user from email notifications
*
* @param $user_id
* @param $group
* @throws Exception
* @return bool
*/
function unsubscribe_user_from_email_notifications( $user_id, $group ) {
$subscriber = get_subscriber( $user_id, $group );
$subscriber_id = !empty($subscriber[0]['es_email_id']) ? $subscriber[0]['es_email_id'] : 0;
return es_cls_dbquery::es_view_subscriber_delete($subscriber_id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment