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

ecfdbz9o  于 2023-10-15  发布在  PHP
关注(0)|答案(1)|浏览(96)
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订阅中的所有其他订阅,但此提供的代码不起作用。请帮助我修复这个代码。
谢谢!2谢谢!

hfwmuf9z

hfwmuf9z1#

您的代码中存在一些错误,因为第一个函数参数是订阅对象,而不是订阅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);
    }
}

代码放在子主题的functions.php文件中(或插件中)。应该可以的
相关:订阅文档-状态更改操作

相关问题