Last active
April 26, 2020 15:33
-
-
Save krasenslavov/f06e54ab014b5d18d9085208b4edc7dd to your computer and use it in GitHub Desktop.
Sending custom emails in WordPress. Visit blog post https://bit.ly/2xlZG9L
This file contains 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
<?php | |
/** | |
$email_custom_data = array( | |
'title' => '', | |
'content' => '', | |
'logo_url' => '', | |
'featured_image_url' => '', | |
'cta_button_url' => '', | |
'cta_button_text' => '', | |
) | |
*/ | |
function compose_email(array $email_custom_data, string $email_address = '') { | |
// If we don't have an email passed then the user must be logged in. | |
if (!$email_address) { | |
$user = get_current_user_id(); | |
if (!$user) { | |
return false; | |
} | |
$curr_user = get_userdata(get_current_user_id()); | |
$email_address = $curr_user->data->user_email; | |
} | |
foreach ($email_custom_data as $key => $value) { | |
$email_custom_data[$key] = html_entity_decode($value); | |
} | |
// Generate our email template and apply all the data from $email_custom_data. | |
ob_start(); | |
include_once 'send_email_template.php'; | |
$email_to = $email_address; | |
$email_subject = $email_custom_data['title']; | |
$email_headers = ['From: Company Name <donotrespond@companyname.com>', 'Cc: support@companyname.com']; | |
$email_body = ob_get_contents(); | |
ob_get_clean(); | |
// Send an email using the wp_mail() function. | |
if (!wp_mail($email_to, $email_subject, $email_body, $email_headers)) { | |
return false; | |
} | |
return true; | |
} | |
function overwrite_email(array $email_data, array $email_custom_data) { | |
foreach ($email_custom_data as $key => $value) { | |
$email_custom_data[$key] = html_entity_decode($value); | |
} | |
// Generate our email template and apply all the data from $email_custom_data. | |
ob_start(); | |
include_once 'send_email_template.php'; | |
$email_data['subject'] = $email_custom_data['title']; | |
$email_data['headers'] = ['From: Company Name <donotrespond@companyname.com>', 'Cc: support@companyname.com']; | |
$email_data['message'] = ob_get_contents(); | |
ob_get_clean(); | |
return $email_data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment