You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现WooCommerce订阅取消按钮的11个月隐藏+1个月显示循环控制

WooCommerce 订阅取消按钮按周期显示/隐藏实现方案

需求:在WooCommerce「我的账户」的订阅详情页面,针对指定产品的订阅,按以下逻辑控制「Cancel」按钮的显示:

  • 订阅开始后前11个月:隐藏取消按钮
  • 第11个月到第12个月期间:显示取消按钮(给用户1个月的取消窗口)
  • 满12个月后,重复上述循环(再隐藏11个月,然后显示1个月,以此类推)

无需依赖第三方插件,基于现有代码修改实现:

function eg_remove_my_subscriptions_button( $actions, $subscription ) {

    $is_my_product = false;
    $specific_products = array( 496875,254616 );
    if ( sizeof( $subscription_items = $subscription->get_items() ) > 0 ) {
        foreach ( $subscription_items as $item_id => $item ) {
            $product = $item->get_product();
            if ( in_array( $product->get_id(), $specific_products ) ) {
                $is_my_product = true;
                break;
            }
        }
    }

    if ( !$is_my_product ) return $actions;

    // 固定隐藏其他指定按钮
    foreach ( $actions as $action_key => $action ) {
        switch ( $action_key ) {
            case 'change_payment_method':
            case 'switch':
            case 'resubscribe':
            case 'pay':
            case 'reactivate':
                unset( $actions[ $action_key ] );
                break;
            default: 
                error_log( '-- $action = ' . print_r( $action, true ) );
                break;
        }
    }

    // 针对Cancel按钮的周期显示逻辑
    if ( isset( $actions['cancel'] ) ) {
        // 获取订阅开始日期
        $start_date = $subscription->get_date( 'start' );
        if ( $start_date ) {
            $start_timestamp = $start_date->getTimestamp();
            $current_timestamp = current_time( 'timestamp' );
            
            // 计算订阅已运行的总月数(按每月30天近似计算)
            $total_months = floor( ( $current_timestamp - $start_timestamp ) / ( 30 * 24 * 60 * 60 ) );
            
            // 计算当前处于12个月循环中的位置(余数范围0-11)
            $cycle_month = $total_months % 12;
            
            // 规则:循环中前10个位置(对应实际第1-11个月)隐藏按钮,后2个位置(第11-12个月)保留
            if ( $cycle_month < 10 ) {
                unset( $actions['cancel'] );
            }
        }
    }

    return $actions;
}
add_filter( 'wcs_view_subscription_actions', 'eg_remove_my_subscriptions_button', 100, 2 );

关键逻辑说明:

  1. 指定产品过滤:保留原有逻辑,仅对$specific_products数组内的产品订阅生效
  2. 时间周期计算:
    • 获取订阅开始时间戳与当前时间戳,计算订阅已运行的总月数
    • 通过取模运算锁定当前在12个月循环中的位置
  3. 按钮显示控制:当循环位置处于0-9区间时(对应订阅后的第1-11个月)隐藏取消按钮,10-11区间(第11-12个月)保留按钮显示

内容的提问来源于stack exchange,提问作者Becca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:49:55