Skip to content

Instantly share code, notes, and snippets.

@martyboggs
Last active January 18, 2019 02:20
Show Gist options
  • Save martyboggs/d6be9b55555662e9091f602fb702c0ea to your computer and use it in GitHub Desktop.
Save martyboggs/d6be9b55555662e9091f602fb702c0ea to your computer and use it in GitHub Desktop.
set up a wordpress email (action must match hook)
<!-- functions.php -->
<?php
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script('main', plugins_url( 'main.js', __FILE__ ), ['jquery'], '1');
wp_localize_script('main', 'php_vars', [
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce('horses-outsmarting-sharks'),
]);
});
add_action('wp_ajax_sendEmail', 'wp_sendmail');
add_action('wp_ajax_nopriv_sendEmail', 'wp_sendmail');
function wp_sendmail() {
check_ajax_referer('horses-outsmarting-sharks', 'security');
$foo = sanitize_text_field($_POST['foo']);
$to = sanitize_email($_POST['email']);
$subject = 'hi';
$headers = ['Content-Type: text/html; charset=UTF-8'];
$body = 'hi there ' . $foo;
// optionally create an html template
// $opts = ['http' => ['header' => "User-Agent:MyAgent/1.0\r\n"]];
// $context = stream_context_create($opts);
// $body = file_get_contents(__DIR__ . '/template.html', false, $context);
// $body = str_replace('*|FOO|*', $foo, $body);
wp_mail($to, $subject, $body, $headers);
echo json_encode(['result' => 'success']);
wp_die();
}
?>
<!-- main.js -->
<script>
$(function () {
$('.send-email').click(sendEmailTemplate);
});
function sendEmailTemplate(e) {
$.post(php_vars.ajax_url, {
action: 'sendEmail',
security: php_vars.ajax_nonce,
email: '[email protected]',
foo: 'bar'
}, function (result) {
console.log(result);
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment