当创建默认的 WooCommerce 新订单时,我试图向所需的电子邮件地址发送一封额外的电子邮件。并希望默认的新订单仍然有效。一切都很好,也收到了电子邮件。
但是对于自定义电子邮件,我没有收到订单详细信息 - 我只想要商品详细信息,没有价格、客户备注以及订单号和日期。
这是代码:
add_action( 'woocommerce_new_order', 'send_custom_order_email', 10, 1 );
function send_custom_order_email( $order_id ) {
// Get the order object
$order = wc_get_order( $order_id );
// Prepare order details without prices
$order_details = '';
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product();
$product_name = $product ? $product->get_formatted_name() : $item['name'];
$item_quantity = $item->get_quantity();
$order_details .= "Product: $product_name - Quantity: $item_quantity\n";
}
// Include the desired details in the email content
$details_to_include = "Order Date: {$order->get_date_created()->format( 'F j, Y' )}\nOrder Number: {$order->get_order_number()}\n\nOrder Details:\n$order_details\nCustomer Note: {$order->get_customer_note()}\n";
// Email subject and content
$email_subject = 'New Order: ' . $order->get_order_number();
$email_content = $details_to_include;
// Email recipient
$desired_email = '[email protected]'; // Replace with the desired email address
// Send the desired email with the order details
wp_mail( $desired_email, $email_subject, $email_content );
}
尝试以下重新访问和增强的代码版本:
add_action( 'woocommerce_new_order', 'send_custom_new_order_email', 10, 2 );
function send_custom_new_order_email( $order_id, $order = null ) {
// Get the order object if it doesn't exist
if ( ! $order && $order_id > 0 ) {
$order = wc_get_order( $order_id );
}
$order_details = ''; // Initialize
// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product(); // get the WC_Product Object
$product_name = $product ? strip_tags($product->get_formatted_name()) : $item->get_name(); // Product name
// Add to the order details (for each item)
$order_details .= "Product: {$product_name} - Quantity: {$item->get_quantity()}\n";
}
// Email content: Include the desired details below
$email_content = "Order Date: {$order->get_date_created()->format( 'F j, Y' )}\n";
$email_content .= "Order Number: {$order->get_order_number()}\n\n";
$email_content .= "Order Details:\n{$order_details}\n";
$email_content .= "Customer Note: {$order->get_customer_note()}\n";
// Email subject
$email_subject = 'New Order: ' . $order->get_order_number();
// Email recipient: Replace with the desired email recipient
$desired_email = '[email protected]';
// Avoid sending the same email multiple times
if( did_action('woocommerce_new_order') == 1 ) {
// Send the desired email with the order details
wp_mail( $desired_email, $email_subject, $email_content );
}
}
这次它将显示购买的产品名称(带数量)并避免多次发送同一封电子邮件。