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

如何在WooCommerce Subscriptions重新订阅流程中添加关联简单产品?

解决方案

要在重新订阅时自动把关联的简单产品加入结账购物车,你可以用WooCommerce Subscriptions提供的wcs_restore_subscription_cart_items钩子——这个钩子会在重新订阅流程中,系统把原订阅商品恢复到购物车的环节触发,刚好适合用来插入额外商品。

基础实现代码

// 重新订阅恢复购物车时添加关联简单产品
add_action( 'wcs_restore_subscription_cart_items', 'add_associated_simple_product_on_resubscribe', 10, 2 );
function add_associated_simple_product_on_resubscribe( $subscription, $cart_items ) {
    // 替换成你的关联简单产品ID
    $target_product_id = 123;
    $target_product = wc_get_product( $target_product_id );

    // 验证产品存在且未在购物车中,避免重复添加
    if ( $target_product && ! WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $target_product_id ) ) ) {
        WC()->cart->add_to_cart( $target_product_id );
    }
}

代码说明

  • wcs_restore_subscription_cart_items:专门对应重新订阅的购物车恢复流程,参数包含当前订阅对象和待加入购物车的原订阅商品数组。
  • 先通过wc_get_product确认目标简单产品有效,再用find_product_in_cart检查购物车中是否已有该产品,防止重复添加。
  • 最后调用add_to_cart把产品加入购物车。

自定义定价场景适配代码

如果你的简单产品需要自定义定价,可以在添加时同步设置价格,或者用额外钩子确保结账时价格生效:

// 重新订阅时添加带自定义定价的简单产品
add_action( 'wcs_restore_subscription_cart_items', 'add_custom_priced_product_on_resubscribe', 10, 2 );
function add_custom_priced_product_on_resubscribe( $subscription, $cart_items ) {
    $target_product_id = 123;
    $custom_price = 9.99; // 替换成你的自定义定价

    if ( ! WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $target_product_id ) ) ) {
        $cart_item_key = WC()->cart->add_to_cart( $target_product_id );
        
        // 立即设置自定义价格
        if ( $cart_item_key ) {
            WC()->cart->cart_contents[ $cart_item_key ]['data']->set_price( $custom_price );
        }
    }
}

// 确保结账时自定义价格生效
add_action( 'woocommerce_before_calculate_totals', 'lock_custom_price_on_resubscribe_checkout' );
function lock_custom_price_on_resubscribe_checkout( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
    // 判断当前是否为重新订阅场景(通过购物车中的订阅商品识别)
    $is_resubscribe = false;
    foreach ( $cart->get_cart() as $item ) {
        if ( wcs_is_subscription_product( $item['product_id'] ) ) {
            $is_resubscribe = true;
            break;
        }
    }

    if ( $is_resubscribe ) {
        $target_product_id = 123;
        $custom_price = 9.99;
        foreach ( $cart->get_cart() as $item ) {
            if ( $item['product_id'] == $target_product_id ) {
                $item['data']->set_price( $custom_price );
            }
        }
    }
}

注意事项

  • 把代码里的$target_product_id和$custom_price替换成你实际的产品ID和定价。
  • 代码可以添加到主题的functions.php文件,或者自定义插件中。
  • 测试前记得备份网站,避免出现意外问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:40:09