I'm currently working on a project that involves implementing a notification button to alert our drivers via email when an order is ready for pickup. However, I've encountered a puzzling issue that has left me scratching my head.
Here's the situation: Whenever the notification button is clicked, the order status inexplicably changes to 'pending payment.' This is not the desired behavior, and I'm struggling to pinpoint the root cause of this problem.
add_action( 'woocommerce_admin_order_data_after_order_details', 'send_driver_email_on_order_ready' );
function send_driver_email_on_order_ready( $order_id ) {
$order = wc_get_order( $order_id );
$id=$order->get_ID();
$status = $order->get_status();
$meta_data = $order->get_meta_data();
if($status=='processing' || 'driver-assigned' || 'out-for-delivery'){
foreach ( $meta_data as $meta ) {
if ( $meta->key === 'lddfw_driverid' ) {
$driver_id = $meta->value;
}
if ( $meta->key === 'Order_Ready' ) {
$order_ready_value = $meta->value;
if ( $order_ready_value === 'Yes' ) {
// Check if email has already been sent
$email_sent = $order->get_meta( 'email_sent', true );
if ( $email_sent != 'Yes' ) {
// Get driver information
$driver = get_userdata( $driver_id );
$driver_name = $driver->display_name;
$driver_email = $driver->user_email;
// Send email to driver
$subject = 'Order no.' . $id . ' ready for pickup';
$message = 'Hello ' . $driver_name . ',<br><br> Order no.' . $id . ' is now ready for pickup.';
$headers = array( 'Content-Type: text/html; charset=UTF-8' );
if ( wp_mail( $driver_email, $subject, $message, $headers ) ) {
// Update email_sent meta value
$order->update_meta_data( 'email_sent', 'Yes' );
$order->save();
}
}
}
}
}
}
}
add_filter('wp_mail_from', 'original_mail_address_email');
function original_mail_address_email(){
$email ='[email protected]';
return $email;
}
add_filter('wp_mail_from_name', 'email_name_order_ready');
function email_name_order_ready(){
return 'Oven Fresh';
}
In addition to this challenge, I'd like to refine the functionality of the button. Ideally, I want the button to be displayed only when the order status is 'driver assigned' or 'out for delivery.' This would streamline the process and make it more efficient for our team.
Any assistance, insights, or suggestions you can provide would be greatly appreciated. Your help would be nothing short of a blessing.
There are some mistakes, unnecessary complications and missing things.
The following will display a button to send an email notification to the driver for specific order statuses on:
When the email is sent, a success message replaces the button and an admin note is set. When an email has been sent, "Email sent" string is displayed instead of the button.
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
Screenshot of the email sent: