自动将 Woocommerce 订阅状态​​更改为 "On-Hold" 而不是 "Active"

Auto change Woocommerce Subscriptions status to "On-Hold" rather than "Active"

在 Woocommerce 中,我想在订单仍为 "processing" 时自动放置所有 Woocommerce 订阅 "on hold" 而不是 "active"。一旦我将订单标记为 "completed",订阅应更改为 "active"。

我已经尝试了所有我能想到的方法,如果有人知道如何做到这一点,请告诉我。

我是 运行 wordpress 4.8.1 / Woocommerce 3.1.2 / Woocommerce Subscriptions 2.2.7 / 支付网关是 Stripe 3.2.3。

这可以分两步完成:

1) 在 woocommerce_thankyou 操作挂钩中使用自定义函数,当订单具有 'processing' 状态并包含订阅时,我们 更新订阅状态为'on-hold':

add_action( 'woocommerce_thankyou', 'custom_thankyou_subscription_action', 50, 1 );
function custom_thankyou_subscription_action( $order_id ){
    if( ! $order_id ) return;

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

    // If the order has a 'processing' status and contains a subscription 
    if( wcs_order_contains_subscription( $order ) && $order->has_status( 'processing' ) ){

        // Get an array of WC_Subscription objects
        $subscriptions = wcs_get_subscriptions_for_order( $order_id );
        foreach( $subscriptions as $subscription_id => $subscription ){
            // Change the status of the WC_Subscription object
            $subscription->update_status( 'on-hold' );
        }
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

2) 在woocommerce_order_status_completed action hook中使用自定义函数,当订单状态变为"completed"时,将自动更改订阅状态为"active":

// When Order is "completed" auto-change the status of the WC_Subscription object to 'on-hold'
add_action('woocommerce_order_status_completed','updating_order_status_completed_with_subscription');
function updating_order_status_completed_with_subscription($order_id) {
    $order = wc_get_order($order_id);  // Get an instance of the WC_Order object

    if( wcs_order_contains_subscription( $order ) ){

        // Get an array of WC_Subscription objects
        $subscriptions = wcs_get_subscriptions_for_order( $order_id );
        foreach( $subscriptions as $subscription_id => $subscription ){
            // Change the status of the WC_Subscription object
            $subscription->update_status( 'active' );
        }
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

所有代码都在 Woocommerce 3+ 上测试并且有效。