购买新订阅后,如何自动取消以前的WooCommerce订阅?

时间:2019-11-13 16:45:47

标签: php wordpress woocommerce woocommerce-subscriptions

我正在建立一个会员站点,其中用户一次只能拥有一个有效的订阅。我希望在购买任何新订阅/产品时,所有其他订阅都将被取消/过期,而所有相关联的会员资格都将被删除/取消。只有最新的订阅及其附带的会员资格才能保持活动状态。

出于某些原因,我不能/不想使用内置功能来限制订阅。

在“谢谢”页面上,是否有任何方式可以使当前用户的所有活动订阅中出现一个被抢断的循环,并取消/终止这些订阅(除了刚刚购买的订阅之外)?

我已经检查了该帖子,该帖子看起来很相似,但是没有提供真正的解决方案(WooCommerce Subscriptions - Only Allow user one active subscription

非常感谢您的帮助

最诚挚的问候

2 个答案:

答案 0 :(得分:0)

在其他SO帖子的帮助下,我已经设法自动解决了问题。

基本上,我通过降序获取ID并在循环中设置一个计数器来获取所有活动订阅。如果循环不止一次,则它将订阅的状态设置为已取消。我将其钩在“谢谢”页面中,以确保仅在付款后才会触发...

nx.graph_edit_distance

不确定这是否是“ Wordpress / WooCommerce”方法,但是我为此带来了其他编程语言的经验。如果有人有更好的主意,请随时发布。

答案 1 :(得分:0)

我修改了下面提到的代码,因为如果新用户注册,它会取消所有订阅,虽然提到的代码适用于现有用户,但当新用户注册时,所有用户的所有订阅都将被取消 因此我将代码开发为

    function edf_cancel_previous_active_subscription() {
    
        $no_of_loops = 0;
        $user_id = get_current_user_id();
       
        // If is an existing user
        if($user_id!=0)
        {
        $args = array(
            'subscription_status'       => 'active', 
            'subscriptions_per_page'    => -1,
            'customer_id'               => $user_id, 
            'orderby'                   => 'ID', 
            'order'                     => 'DESC'
        );
        $subscriptions = wcs_get_subscriptions($args);
        // Going through each current customer subscriptions
         foreach ( $subscriptions as $subscription ) {
             $no_of_loops = $no_of_loops + 1;
//Cancel previous subscription of user applying for new subscription
             if ($no_of_loops = 1) {
                 $subscription->update_status( 'pending-cancel' );
             }
         }
     }
    }
//when checkout is in progress previous subscriptions will be cancelled and after successful checkout the subscription for which checkout process was initiated becomes active
    add_action('woocommerce_before_checkout_process', 'edf_cancel_previous_active_subscription');