WooCommerce order status hook not triggering

守給你的承諾、 提交于 2019-12-24 10:01:54

问题


I'm using this little function here to detect if an order is set into pending. This happens between the payment page and the payment provider notification:

add_action( 'woocommerce_order_status_pending', 'status_pending' );
function status_pending( $related_job ) {
    error_log('Triggered');
}

The problem is that I don't get any error log which shows me that the function work. But it becomes crazier. When I update the status via the dashboard from completed to pending, the log appears. So I've absolutely no idea why it's not working during the checkout process. Any recommendations or ideas what could be the problem?


回答1:


The "pending" order status is the default status for orders before customer get on a payment gateway, just after order creation.

So the best way is to use a hook once the order is created, before payment method process:

1) try first the woocommerce_checkout_order_processed action hook (3 args):

add_action( 'woocommerce_checkout_order_processed', 'order_processed_with_pending_status', 10, 3 );
function order_processed_with_pending_status( $order_id, $posted_data, $order ) {
    error_log('Triggered');
}

2) Alternatively try the woocommerce_checkout_update_order_meta action hook (2 args):

add_action( 'woocommerce_checkout_update_order_meta', 'order_processed_with_pending_status', 10, 2 );
function order_processed_with_pending_status( $order_id, $data ) {
    error_log('Triggered');
}

Both should work…




回答2:


That's because the hook is only triggering on order status change not on order creation, there is another hook that you can use to detect new orders, you can use the order ID to get order object which you can use to find out the order status:

add_action( 'woocommerce_new_order', 'prefix_new_wc_order',  1, 1  );
function prefix_new_wc_order( $order_id ) {
    $order = new WC_Order( $order_id );

}

The hook above is only triggered in checkout process, so creating orders on backend won't trigger it.



来源:https://stackoverflow.com/questions/56263261/woocommerce-order-status-hook-not-triggering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!