我试图在每次下订单后给自己发送电子邮件。我遇到的问题是$order->get_total()
以及get_total_tax
返回 0 而不是实际订单总价值。
add_action( 'woocommerce_new_order', 'custom_after_order_created_hook', 12 , 1);
function custom_after_order_created_hook($order_id) {
$order = new WC_Order($order_id);
$with_tax = $order->get_total();
$tax = $order->get_total_tax();
$without_tax = $with_tax - $tax;
$to = "test@example.com";
$subject = "New order";
$content = "
New order {$order->id}
With tax: {$with_tax}
Without tax: {$without_tax}
Tax: {$tax}
";
$status = wp_mail($to, $subject, $content);
}
$ order_id和$order->id
之外的每个值都被评估为0. $ order_id具有适当的值。只有在使用woocommerce_new_order
挂钩时才会出现此问题(我也尝试在自定义页面上使用它 - 正常工作),这让我很奇怪。
我不知道这里的问题是什么,我的代码的某些部分是异步的吗?
或者也许在订单获得价格支付/税收信息更新之前调用此挂钩?
我该怎么办才能在这里获得价格信息?
感谢。
答案 0 :(得分:4)
这个woocommerce_new_order动作钩子用于改变create_order()函数。因此,您最好使用 woocommerce_thankyou
操作挂钩,以便在创建订单时触发自定义电子邮件通知:
// Tested on WooCommerce versions 2.6+ and 3.0+
add_action( 'woocommerce_thankyou', 'new_order_custom_email_notification', 1, 1 );
function new_order_custom_email_notification( $order_id ) {
if ( ! $order_id ) return;
// Getting an instance of WC_Order object
$order = wc_get_order( $order_id );
$with_tax = $order->get_total();
$tax = $order->get_total_tax();
$without_tax = $with_tax - $tax;
$to = "test@example.com";
$subject = "New order";
$content = "
New order {$order_id}
With tax: {$with_tax}
Without tax: {$without_tax}
Tax: {$tax}
";
wp_mail($to, $subject, $content);
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
代码经过测试并有效。
使用
woocommerce_checkout_order_processed
操作挂钩代替woocommerce_thankyou
操作挂钩也是一个不错的选择,可能会更好。你只需要替换:add_action( 'woocommerce_thankyou', 'new_order_custom_email_notification', 1, 1 );
人:
add_action( 'woocommerce_checkout_order_processed', 'new_order_custom_email_notification', 1, 1 );
类似的工作答案:Woocommerce - How to send custom emails based on payment type
woocommerce_checkout_order_processed
方法(位于WC_Checkout process_checkout()
方法中,为此目的也很方便。获取购买流程的观点时,
WC_Checkout process_checkout()
方法的源代码很有意思。