【问题标题】:Hook woocommerce_thankyou doesn't receive order挂钩 woocommerce_thankyou 未收到订单
【发布时间】:2017-11-30 15:20:29
【问题描述】:

在 WooCommerce 中,我使用挂钩在 woocommerce_thankyou 操作挂钩中的自定义函数,在付款后执行一些代码。钩子有效,但我似乎无法获得订单。

这是简化的代码。从外观上看,没有找到 $order

add_action( 'woocommerce_thankyou', 'afterorder', 10, 1 );


function afterorder($order_id) {
    //$order = new WC_Order($order_id);
    $order = wc_get_order($order_id);
    $order_items = $order->get_items();
    $order_comment_list = explode('\n', $order->customer_message);
    $payment_method = $order->payment_method_title; 

    foreach( $order_items as $product ) {
        $order->add_order_note('order for '.$product['name'].' received', false);
    }
}

我在这里错过了什么?

【问题讨论】:

    标签: php wordpress woocommerce product orders


    【解决方案1】:

    自 WooCommerce 3+ 以来,您的代码已部分过时并存在一些错误。订单行项目现在是 WC_Order_Item_Product 类对象。

    对于订单“订单项”,您需要使用WC_Order_Item_Product可用的方法来获取相关数据,例如对应的产品标题:

    add_action( 'woocommerce_thankyou', 'afterorder', 10, 1 );
    function afterorder( $order_id ) {
        // The WC_Order object
        $order = wc_get_order($order_id);
    
        $order_comment_list = explode( '\n', $order->get_customer_note() ); // Changed
    
        $payment_method = $order->get_payment_method_title(); // Changed 
    
        foreach( $order->get_items() as $line_item ) {
            // The WC_Product object
            $product = $line_item->get_product(); // Added
            $note = 'order for '.$product->get_title().' received';// Changed
            $order->add_order_note( $note, false );
        }
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件或任何插件文件中。

    您应该检查WC_Order 方法add_order_note(),看看您是否正确设置了它。

    【讨论】:

    • 不错!优秀的答案。值得一提的是10, 1add_action 的默认值,因此没有必要....add_action( 'woocommerce_thankyou', 'afterorder' )...
    • @cale_b 当编码更好地设置优先级和参数数量时,原因有很多。有点像严格的变量声明......但你是对的。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2016-02-12
    • 2017-10-10
    • 1970-01-01
    • 2021-04-21
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多