php - 在新订单 Hook 中获取订单数据

标签 php wordpress woocommerce hook-woocommerce orders

我尝试在每次下订单后给自己发送一封电子邮件。我遇到的问题是 $order->get_total() 以及 get_total_tax 返回 0 而不是实际的订单总值(value)。

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 Hook 时发生(我也尝试在自定义页面上使用它 - 工作正常),这让我感到奇怪。

我不确定这里的问题是什么,我的代码的某些部分是异步的吗?
或者这个 Hook 可能在订单更新为已付价格/税收信息之前被调用?
我应该怎么做才能在此处获取价格信息?

谢谢。

最佳答案

这个 woocommerce_new_order Action Hook 用于改变 create_order() 函数。因此,您最好使用 woocommerce_thankyou 操作 Hook ,它会在创建订单时触发您的自定义电子邮件通知:

// 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 文件或任何插件文件。

代码已经过测试并且可以工作。

Using woocommerce_checkout_order_processed action hook instead of woocommerce_thankyou action hook is also a good alternative, may be even better. You have just to replace:

add_action( 'woocommerce_thankyou', 'new_order_custom_email_notification', 1, 1 );

By:

add_action( 'woocommerce_checkout_order_processed', 'new_order_custom_email_notification', 1, 1 );

类似的工作答案:Woocommerce - How to send custom emails based on payment type


The woocommerce_checkout_order_processed hook (located in WC_Checkout process_checkout() method that could be convenient too for this purpose.

The source code of WC_Checkout process_checkout() method is interesting to get a view on the purchase flow.

关于php - 在新订单 Hook 中获取订单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43416512/

相关文章:

php - Wordpress 添加评论栏并保存自定义数据

wordpress - WordPress的。 Woocommerce。 Action Hook 在添加到购物车之前

PHP 和 MySQL WP

mysql - $wpdb - 按两个元值排序

php - 如何使用 Laravel 制作自定义主题以及存储主题数据的位置?

php - 为什么我的产品不能环绕我的形象?我需要它们环绕我的 float 图像

woocommerce - 如何像使用普通 php session 一样在 woocommerce 页面中使用 session ?

PHP 尝试获取非对象的属性

php - 利用 ? (问号)代替/使用 Slim Framework

php - 用户输入的字符破坏了 xml_parse_into_struct 完成的 xml 解码