【问题标题】:Auto change Woocommerce Subscriptions status to "On-Hold" rather than "Active"自动将 Woocommerce 订阅状态​​更改为“暂停”而不是“活动”
【发布时间】:2023-03-08 18:45:01
【问题描述】:

在 Woocommerce 中,我想在订单仍在“处理”时自动将所有 Woocommerce 订阅“暂停”而不是“活动”。一旦我将订单标记为“已完成”,该订阅应更改为“有效”。

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

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

【问题讨论】:

    标签: php wordpress woocommerce orders woocommerce-subscriptions


    【解决方案1】:

    这可以分两步完成:

    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 动作钩子中挂钩自定义函数,当订单状态变为“已完成”时,它会自动更改订阅状态为“活跃”

    // 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+ 上进行了测试并且可以运行。

    【讨论】:

    猜你喜欢
    • 2018-09-19
    • 2019-04-16
    • 2018-08-23
    • 2019-04-09
    • 2021-05-23
    • 2022-10-05
    • 2020-11-14
    • 2018-08-01
    • 2019-06-01
    相关资源
    最近更新 更多