It is necessary to make sure that when sending the form, the person receives a promo code that is generated specifically for him. The problem is, the letter arrives, the promo code is generated, but the promo code is not inserted in the letter. WordPress site, woocomerce, storefront theme, I use contact form7 for the form. That’s what I’ve come to, in function.php My topic:
// Обработка формы после отправки
function process_form_after_submission($contact_form) {
// Получаем значения из формы
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$posted_data = $submission->get_posted_data();
// Получаем значение поля "E-mail"
$email = isset($posted_data['email-504']) ? sanitize_email($posted_data['email-504']) : '';
// Генерируем уникальный промокод
$coupon_code = generate_unique_coupon($email);
if ($coupon_code) {
// Устанавливаем параметры промокода (ваша дата и сумма могут отличаться)
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon',
'post_excerpt' => 'Промокод для ' . $email,
);
// Создаем промокод
$new_coupon_id = wp_insert_post($coupon);
// Устанавливаем сумму скидки и ограничения
update_post_meta($new_coupon_id, 'discount_type', 'fixed_cart');
update_post_meta($new_coupon_id, 'coupon_amount', 1000);
update_post_meta($new_coupon_id, 'individual_use', 'yes');
update_post_meta($new_coupon_id, 'usage_limit', 1);
update_post_meta($new_coupon_id, 'expiry_date', strtotime('+1 week'));
// Сохраняем промокод в сессии для использования в блоке благодарности
WC()->session->set('generated_coupon', $coupon_code);
}
}
}
add_action('wpcf7_mail_sent', 'process_form_after_submission');
// Заменяем шорткод [generated_coupon] на значение из сессии
function replace_generated_coupon_shortcode($content) {
return str_replace('[generated_coupon]', WC()->session->get('generated_coupon'), $content);
}
add_filter('wpcf7_mail_tag_replaced', 'replace_generated_coupon_shortcode', 10, 3);
// Генерация уникального промокода
function generate_unique_coupon($email) {
$coupon_code = 'DISCOUNT_' . wp_generate_password(8, false);
// Дополнительные проверки, чтобы избежать конфликтов
$existing_coupon = get_page_by_title($coupon_code, OBJECT, 'shop_coupon');
if ($existing_coupon) {
// Если промокод с таким кодом уже существует, генерируем новый
return generate_unique_coupon($email);
}
return $coupon_code;
}
2
Answers
Your handler for
wpcf7_mail_sent
creates the coupon code and sets it in the session, your handler forwpcf7_mail_tag_replaced
reads from the session and replaces it into the email.However,
wpcf7_mail_tag_replaced
hook will fire beforewpcf7_mail_sent
, and therefore the coupon won’t have been created at that point.You’d have to create the post/write the code to session in a hook which fires earlier in the process (I think
wpcf7_posted_data
may be suitable for this)