I am working on a marketplace plugin. If the vendors do not accept the order within the date range I set, the order will be cancelled. For this, I have determined a time period of order date +3 days. So far, so good.
For example,
deadline ( $last_time): 1623593126
Today: $now // (unix today)
Order Code: $order_number
According to the scenario above, I am sending an e-mail to an e-mail address by using wp_mail that the order was not accepted.
The problem starts here. WordPress mail not working as I want. If the scenario is realized, that is, if the vendor does not accept the order, an e-mail is sent. However, every time the page is refreshed, this mail comes again and again. How can I prevent this? Therefore, the mail should come only once.
I would be glad if you help. I’ve been searching for about 3 days but couldn’t find a solution.
My code is below:
foreach ( $user_orders as $order ) {
//...codes...
if($now>$last_time) {
$order_number = $order->get_order_number();
$to = '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13766b727e637f7653766b727e637f763d707c7e">[email protected]</a>';
$subject = 'Failed order ';
$body = '#'.$order_number. ' order number failed;
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
}
//...codes...
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use meta to create a one time action
something like this
$order_id = $order->get_id(); if (get_post_meta($order_id, 'is_mail_sent', true)) return; update_post_meta($order_id, 'is_mail_sent', true);
Add this right after the opening of the if block
This code will first check if the order meta value of is_mail_sent is true, if true it will return (exit) from the funcion.
If it was not true, first time, then it will continue to the rest of the code and also set the is_mail_sent to true to prevent future mail sending
You could also do this
$order_id = $order->get_id();
if($now>$last_time && !get_post_meta($order_id, 'is_mail_sent', true)) {
update_post_meta($order_id, 'is_mail_sent', true);
$order_number = $order->get_order_number();
$to = '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8aeff2ebe7fae6efcaeff2ebe7fae6efa4e9e5e7">[email protected]</a>';
$subject = 'Failed order ';
$body = '#'.$order_number. ' order number failed;
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
}
This will perform the same check but will only wrap the mail part of the code
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0