add_shortcode( 'ccom_klaviyo_notify', function() {
add_action( 'wp_print_footer_scripts', function() {
?>
<script type="text/javascript">
window.addEventListener( 'klaviyoForms', function( e ) {
if( e.detail.type != 'submit' ) {
return;
}
if( e.detail.formId != '######' ) {
return;
}
let request = new XMLHttpRequest();
request.open( 'POST', '/wp-admin/admin-ajax.php', true );
var data = new FormData();
data.append( 'action', 'ccom_klaviyo_notify' );
data.append( 'first_name', e.detail.metaData.$first_name ),
data.append( 'last_name', e.detail.metaData.$last_name ),
data.append( 'email', e.detail.metaData.$email ),
request.send( data );
} );
</script>
<?php
} );
} );
add_action( 'wp_ajax_ccom_klaviyo_notify', 'ccom_klaviyo_notify' );
add_action( 'wp_ajax_nopriv_ccom_klaviyo_notify', 'ccom_klaviyo_notify' );
function ccom_klaviyo_notify() {
$args = [
'to' => '[email protected]',
'from' => '[email protected]',
'message' => 'This is a Klaviyo form submission notification.',
'first_name' => sanitize_text_field( $_POST['first_name'] ),
'last_name' => sanitize_text_field( $_POST['last_name'] ),
'email' => sanitize_email( $_POST[ 'email' ] ),
];
$mailbody = wpautop(
sprintf(
"%s\n\n%s %s\n%s",
$args['message'],
$args['first_name'],
$args['last_name'],
$args['email']
)
);
$headers = [
'From: ' . $args['from'],
'Reply-To: ' . $args['email'],
];
wp_mail( $args['to'], $args['subject'], $mailbody, $headers );
wp_die( 'Success' );
}
Klaviyo signup form email notification using wp_mail
How to use
PHP Code Snippets
- Log into a staging, development, or locally hosted clone of your site
- Install and activate Code Snippets
- WP Admin > Snippets > Add New
- Copy and paste the code from the Description tab above
- Check to ensure formatting came over properly and no syntax errors show up in the editor
- Customize the code as desired
- Add a meaningful title
- Select whether to run on front-end or back-end (or both)
- Click “Save and Activate”
- Test your site to ensure it works
- Disable if any problems, or recover
- Repeat for live environment
License
All code snippets are licensed GPLv2 (or later) matching WordPress licensing.
Disclaimer of warranty:
Except when otherwise stated in writing the copyright holders and/or other parties provide the program as-is without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.
Support
- Describe the issue and what you’ve observed.
- Describe your expected outcome(s).
- List steps to reproduce the issue.
- Optionally provide screen-shot or video URLs.
