Woocommerce 订阅:用户取消产品 76 订阅,然后取消所有其他 Woocommerce 订阅

Woocommerce Subscriptions: User cancels product 76 subscription, then cancels all other Woocommerce subscriptions

提问人:Rafay King 提问时间:10/12/2023 最后编辑:LoicTheAztecRafay King 更新时间:10/13/2023 访问量:32

问:

add_action('woocommerce_subscription_status_updated', 'custom_subscription_status_change', 10, 3);

function custom_subscription_status_change($subscription_id, $new_status, $old_status) {
    // Check if it's one of the subscriptions you want to monitor (ID 76)
    if ($subscription_id == 76) {
        // Load the subscription object
        $subscription = wcs_get_subscription($subscription_id);

        // Check if the new status is 'cancelled'
        if ($new_status == 'cancelled') {
            // Cancel the other subscription (ID 77)
            $other_subscription_id = 77;
            $other_subscription = wcs_get_subscription($other_subscription_id);
            
            if ($other_subscription) {
                $other_subscription->cancel_order();
            }
        }
    }
}

当用户同时订阅了产品 76 和产品 77 订阅时,以及从我的帐户/订阅选项卡/操作选项卡取消产品 76 订阅时,然后取消了 WooCommerce 订阅中的所有其他订阅,但此提供的代码不起作用。请帮我修复此代码。

谢谢!

PHP 循环 订单 woocommerce-subscriptions

评论


答:

0赞 LoicTheAztec 10/13/2023 #1

代码中存在一些错误,因为第一个函数参数是订阅对象,而不是订阅 ID。

当客户取消订阅时,若要取消所有其他订阅,请尝试:

add_action('woocommerce_subscription_status_updated', 'custom_subscription_status_change', 10, 3);
function custom_subscription_status_change( $subscription, $new_status, $old_status ) {
    // When a subscription is cancelled by the customer
    if ( $new_status === 'cancelled' && ! is_admin() ) {
        // Remove action to avoid an infinite loop
        remove_action('woocommerce_subscription_status_updated', 'custom_subscription_status_change', 10, 3);

        // Loop through all customer subscriptions
        foreach( wcs_get_users_subscriptions( $subscription->get_user_id() ) as $subscription_id => $subscription ) {
            // Cancel all other subscriptions for the customer
            if ( $subscription->get_id() != $subscription_id && $subscription->get_status() !== 'cancelled' ) {
                $subscription->cancel_order("Subscription {$subscription->get_id()} cancelled by the customer, cancel this subscription.");
            }
        }
        // add back the action
        add_action('woocommerce_subscription_status_updated', 'custom_subscription_status_change', 10, 3);
    }
} 

代码位于子主题的函数.php文件中(或插件中)。它应该起作用。

相关新闻: 订阅文档 - 状态更改操作