在 Woocommerce 中更新状态之前获取最后的旧订单状态

Get last old order status before updated status in Woocommerce

我目前正在寻找一种在更新订单状态之前获取订单状态的方法。


例如,我的订单状态为 in-progress,我使用此处的此功能以编程方式将订单状态更改为 wc-completed:

$order->update_status( 'wc-completed' );

当订单状态为 wc-completed 时,我有一个发送电子邮件的触发器。但是我现在需要检查当前状态之前的状态是否为in-progress。如果这是真的,我需要跳过触发器:

$latest_status = get_order_status_before_current_one($order_id);
if ($latest_status !== 'in-progress') {
    // Triggers for this email.
    add_action( 'woocommerce_order_status_completed_notification', array( $this, 'trigger' ), 1, 2 );
}

我怎样才能达到这个目标?

对于 在使用 $order->update_status( 'wc-completed' ); 更新 订单状态之前,您需要在每个状态更改事件上添加一种状态历史记录,使用以下内容:

add_action( 'woocommerce_order_status_changed', 'grab_order_old_status', 10, 4 );
function grab_order_old_status( $order_id, $status_from, $status_to, $order ) {
    if ( $order->get_meta('_old_status') ) {
        // Grab order status before it's updated
        update_post_meta( $order_id, '_old_status', $status_from );
    } else {
        // Starting status in Woocommerce (empty history)
        update_post_meta( $order_id, '_old_status', 'pending' );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。


USAGE - 那么现在您可以使用以下 IF 语句之一 (带订单 ID):

if( get_post_meta( $order_id, '_old_status', true ) !== 'in-progress' ) { 
    // Your code
}

(带订单对象):

if( $order->get_meta('_old_status') !== 'in-progress' ) { 
    // Your code
}