File: /var/www/kevin-demo/wp-content/themes/fitmencook/includes/brevoEmailSendAjax.php
<?php
add_action('wp_ajax_brevo_email_send', 'brevo_email_send');
add_action('wp_ajax_nopriv_brevo_email_send', 'brevo_email_send');
function brevo_email_send () {
$userEmail = $_POST['userEmail'];
$postUrl = $_POST['postUrl'];
$recipeID = $_POST['recipeID'];
if (empty($userEmail) || empty($postUrl) || empty($recipeID)) {
wp_send_json_error('Missing required data');
return;
}
// Validate email and URL
if (!filter_var($userEmail, FILTER_VALIDATE_EMAIL) || !preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $postUrl)) {
wp_send_json_error('Invalid email or URL format');
return;
}
// Get the recipe post
$recipe_post = get_post($recipeID);
if (!$recipe_post || $recipe_post->post_type !== 'recipes') {
wp_send_json_error('Invalid recipe ID');
return;
}
// Set up the post data for the email template
global $post;
$post = $recipe_post;
setup_postdata($post);
// Get the email template based on recipe template
$recipe_template = get_page_template_slug($recipeID);
ob_start();
if($recipe_template == 'single-recipes-multiple.php') {
get_template_part('template-parts/recipe/newsletter-email-multiple-template', null, [
'recipeID' => $recipeID
]);
}
elseif($recipe_template == 'single-recipes-collection.php') {
get_template_part('template-parts/recipe/newsletter-email-collection-template', null, [
'recipeID' => $recipeID
]);
}
else {
get_template_part('template-parts/recipe/newsletter-email-default-template', null, [
'recipeID' => $recipeID
]);
}
$email_content = ob_get_clean();
// Reset post data
wp_reset_postdata();
// Email headers
$headers = array('Content-Type: text/html; charset=UTF-8');
// Email subject
$subject = 'Saved Recipe: ' . get_the_title($recipeID) . ' - FitMenCook';
// Send the email
$sent = wp_mail($userEmail, $subject, $email_content, $headers);
if ($sent) {
wp_send_json_success('Email sent successfully');
} else {
wp_send_json_error('Failed to send email');
}
die();
}