Hook into WooCommerce Order Status Transitions and Lifecycle Events

Hook into WooCommerce order status transitions

A WooCommerce order moves through statuses: pending, processing, on-hold, completed, cancelled, refunded, failed, plus custom ones from extensions. Every status change fires a predictable set of hooks, so fulfillment, ERP sync, notifications and analytics can react to exactly the transition they need, without save_post and without polling.

Problem: A store has to notify the warehouse API when an order goes to “processing”, send an SMS when it is completed, and log every status change. It is done with one save_post hook, which fires on every save, causes duplicate calls and does not know the previous status.

Solution: Use the WooCommerce status hooks: a transition-specific or status-specific hook for each action, and woocommerce_order_status_changed for the log. Move slow external calls to Action Scheduler.

The three kinds of hooks

  • woocommerce_order_status_changed ($order_id, $old_status, $new_status, $order): every transition;
  • woocommerce_order_status_{new} ($order_id, $order): entering a status from anywhere, e.g. woocommerce_order_status_completed;
  • woocommerce_order_status_{old}_to_{new} ($order_id, $order): one specific transition, e.g. woocommerce_order_status_pending_to_processing.

The statuses in hook names have no wc- prefix.

1. Notify the warehouse, in the background

<?php
add_action( 'woocommerce_order_status_processing', function ( $order_id ) {
    // Do not make the customer wait for the warehouse API: queue the call
    as_enqueue_async_action( 'myplugin_notify_warehouse', array( $order_id ), 'myplugin' );
} );

add_action( 'myplugin_notify_warehouse', function ( $order_id ) {
    $order = wc_get_order( $order_id );
    if ( ! $order || $order->get_meta( '_warehouse_reference' ) ) {
        return; // deleted, or already sent
    }

    $items = array();
    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        $items[] = array(
            'sku'      => $product ? $product->get_sku() : '',
            'quantity' => $item->get_quantity(),
        );
    }

    $response = wp_remote_post( 'https://warehouse.example.com/api/orders', array(
        'timeout' => 15,
        'headers' => array( 'Content-Type' => 'application/json' ),
        'body'    => wp_json_encode( array(
            'order_id' => $order->get_order_number(),
            'name'     => $order->get_formatted_shipping_full_name(),
            'address'  => $order->get_address( 'shipping' ),
            'items'    => $items,
        ) ),
    ) );

    if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
        $order->add_order_note( 'Warehouse notification failed, will retry.' );
        throw new Exception( 'Warehouse API error' ); // Action Scheduler marks the action as failed
    }

    $reference = json_decode( wp_remote_retrieve_body( $response ), true )['reference'] ?? '';
    $order->update_meta_data( '_warehouse_reference', sanitize_text_field( $reference ) );
    $order->add_order_note( 'Warehouse notified. Reference: ' . sanitize_text_field( $reference ) );
    $order->save();
} );

woocommerce_order_status_processing fires for any way into “processing” (from pending, on-hold, failed), and the stored reference makes the action safe to run twice.

2. SMS on completion

<?php
add_action( 'woocommerce_order_status_completed', function ( $order_id, $order ) {
    $phone = preg_replace( '/[^0-9+]/', '', $order->get_billing_phone() );
    if ( ! $phone ) {
        return;
    }

    $message = sprintf(
        __( 'Hi %1$s! Your order #%2$s has shipped: %3$s', 'myplugin' ),
        $order->get_billing_first_name(),
        $order->get_order_number(),
        $order->get_view_order_url()
    );

    as_enqueue_async_action( 'myplugin_dispatch_sms', array( $phone, $message ), 'myplugin' );
}, 10, 2 );

3. Log every change

<?php
add_action( 'woocommerce_order_status_changed', function ( $order_id, $old_status, $new_status, $order ) {
    global $wpdb;
    $wpdb->insert(
        $wpdb->prefix . 'myplugin_order_status_log',
        array(
            'order_id'   => $order_id,
            'old_status' => $old_status,
            'new_status' => $new_status,
            'changed_at' => current_time( 'mysql', true ),
            'user_id'    => get_current_user_id(), // 0 for gateways and cron
        ),
        array( '%d', '%s', '%s', '%s', '%d' )
    );
}, 10, 4 );

A custom status

<?php
add_action( 'init', function () {
    register_post_status( 'wc-awaiting-pickup', array(
        'label'                     => _x( 'Awaiting pickup', 'Order status', 'myplugin' ),
        'public'                    => false,
        'exclude_from_search'       => true,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop( 'Awaiting pickup <span class="count">(%s)</span>', 'Awaiting pickup <span class="count">(%s)</span>', 'myplugin' ),
    ) );
} );

add_filter( 'wc_order_statuses', function ( $statuses ) {
    $statuses['wc-awaiting-pickup'] = _x( 'Awaiting pickup', 'Order status', 'myplugin' );
    return $statuses;
} );

The custom status takes part in the same hooks: woocommerce_order_status_awaiting-pickup, woocommerce_order_status_processing_to_awaiting-pickup and so on.

NOTE: Change the status only through the order object, $order->update_status( 'completed', 'Note' ) or set_status() + save(): that is what fires the hooks. Writing the status directly to the database skips them and, with HPOS, does not even touch the right table (see migrating to HPOS).