Home > Back-end >  No result when using the "woocommerce_new_order" hook when order has status "processi
No result when using the "woocommerce_new_order" hook when order has status "processi

Time:08-07

I need Telegram notifications to be sent when the order status is "Processing", so I have this code:

add_action( 'woocommerce_new_order', 'new_order_send_tg',  1, 1  );
function new_order_send_tg( $order_id ) {
    $order = wc_get_order( $order_id );
    
    $msg .= '✅ Order № '.$order_id . ' *success*';
 
    $userId = '-xxxxxxxxxxxxxx'; // ID Chat
    $token = 'xxxxxxxxxxxxxxxxxxxxxxxx'; // Token bot
    
    if( 'processing' == $order->get_status() ) {
        file_get_contents('https://api.telegram.org/bot'. $token .'/sendMessage?chat_id='. $userId .'&text=' . urlencode($msg) . '&parse_mode=markdown'); // Send
    } else {
        // 
    }
}

Without the if( 'processing' == $order->get_status() ) condition, everything works as expected. But with the if condition added this doesn't seem to be the case. Any advice?

CodePudding user response:

It looks like the woocommerce_new_order hook is executed before the order status is changed to processing

function action_woocommerce_new_order( $order_id, $order = null ) {
    // Get order
    $order = is_a( $order, 'WC_Order' ) ? $order : wc_get_order( $order_id );    

    $status = $order->get_status();

    // Result: status = pending
}
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 2 );

So you can use the woocommerce_order_status_' . $status_transition['to'] composite action hook instead, where you will replace $status_transition[to] by processing

function action_woocommerce_order_status_processing( $order_id, $order ) {
    // Do your thing
}
add_action( 'woocommerce_order_status_processing', 'action_woocommerce_order_status_processing', 10, 2 );
  • Related