Untitled
unknown
plain_text
a year ago
2.7 kB
23
Indexable
<?php
// Schedule the daily check
add_action('wp', 'schedule_customer_reminder');
function schedule_customer_reminder() {
if (!wp_next_scheduled('send_customer_reminder_emails')) {
wp_schedule_event(time(), 'daily', 'send_customer_reminder_emails');
}
}
// The main function that sends reminder emails
add_action('send_customer_reminder_emails', 'send_customer_reminder_emails');
function send_customer_reminder_emails() {
global $wpdb;
// Find customers who haven't ordered in 7 days
$query = $wpdb->prepare("
SELECT DISTINCT pm.meta_value as customer_email,
u.display_name as customer_name
FROM {$wpdb->prefix}posts p
JOIN {$wpdb->prefix}postmeta pm ON p.ID = pm.post_id
LEFT JOIN {$wpdb->users} u ON pm.meta_value = u.user_email
WHERE p.post_type = 'shop_order'
AND pm.meta_key = '_billing_email'
AND p.post_date < %s
AND p.post_date > %s
GROUP BY pm.meta_value
HAVING MAX(p.post_date) < %s
",
current_time('mysql'),
date('Y-m-d H:i:s', strtotime('-30 days')), // Only check last 30 days
date('Y-m-d H:i:s', strtotime('-7 days')) // No orders in 7 days
);
$inactive_customers = $wpdb->get_results($query);
// Get WooCommerce mailer
$mailer = WC()->mailer();
foreach ($inactive_customers as $customer) {
// Email content
$subject = 'We miss you at ' . get_bloginfo('name');
// Your email content
$content = sprintf(
"Hello %s,<br><br>" .
"We noticed it's been a while since your last order at %s. " .
"We'd love to see you back!<br><br>" .
"Check out our latest products: <a href='%s'>Visit our shop</a><br><br>" .
"Best regards,<br>" .
"%s Team",
$customer->customer_name ?: 'valued customer',
get_bloginfo('name'),
get_site_url() . '/shop',
get_bloginfo('name')
);
// Wrap the content with WooCommerce template
$formatted_email = $mailer->wrap_message(
// Email heading
'We Miss You!',
// Email content
$content
);
// Send the email using WooCommerce mail template
$mailer->send(
$customer->customer_email,
$subject,
$formatted_email,
array('Content-Type: text/html; charset=UTF-8')
);
}
}
// Optional: Function to clean up the scheduled event when theme is deactivated
add_action('switch_theme', 'cleanup_reminder_schedule');
function cleanup_reminder_schedule() {
wp_clear_scheduled_hook('send_customer_reminder_emails');
}Editor is loading...
Leave a Comment