自动将Woocommerce订阅状态更改为"暂停"而不是"活跃"

时间:2017-09-17 13:16:19

标签: php wordpress woocommerce orders woocommerce-subscriptions

在Woocommerce中,我想自动将所有Woocommerce订阅和#34;暂停"而不是"活跃"当订单仍处于"处理"。一旦我将订单标记为"已完成"该订阅应更改为"活动"。

我已经尝试了我能想到的一切,如果有人知道怎么做,请告诉我。

我正在运行wordpress 4.8.1 / Woocommerce 3.1.2 / Woocommerce订阅2.2.7 /并且支付网关是Stripe 3.2.3。

1 个答案:

答案 0 :(得分:4)

这可以分两步完成:

1)当一个自定义功能挂钩在 woocommerce_thankyou 动作挂钩中,当订单有一个'处理'状态并包含订阅,我们更新订阅状态为'暂停'

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 操作挂钩中的自定义功能,当订单状态更改为&#34;已完成&#34;时,它将自动更改< / strong>订阅状态为&#34;有效&#34;

// 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+上进行测试并且有效。