Wordpress 如何根据商业订单中使用的优惠券更改订单状态

Wordpress 如何根据商业订单中使用的优惠券更改订单状态,wordpress,woocommerce,Wordpress,Woocommerce,我想在下单后更改订单中使用的特定优惠券的保留状态。我找到了一些可以更改订单状态的代码,但我不知道如何从订单中检查优惠券代码。尝试此代码 add_action('woocommerce_thankyou', 'change_order_status_based_on_coupon', 10, 1); function change_order_status_based_on_coupon( $order_id ) { if ( ! $order_id ) return;

我想在下单后更改订单中使用的特定优惠券的保留状态。我找到了一些可以更改订单状态的代码,但我不知道如何从订单中检查优惠券代码。

尝试此代码

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

function change_order_status_based_on_coupon( $order_id ) {

    if ( ! $order_id )
        return;

    // Getting an instance of the order object
    $order = wc_get_order( $order_id );

    // Coupons used in the order LOOP 
    foreach( $order->get_used_coupons() as $coupon_code ){

        // Retrieving the coupon ID
        $coupon_obj = get_page_by_title( $coupon_code, OBJECT, 'shop_coupon' );
        $coupon_id  = $coupon_obj->ID;

        // Get an instance of WC_Coupon object
        $coupon = new WC_Coupon($coupon_id);

        // Now you can get code in your condition
        if ( $coupon->get_code() == 'Your coupon code' ){
            $order->update_status('Your order status', 'order_note'); // order note is optional, if you want to  add a note to order
            break;
        }
        
    }
}