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

WordPress自定义订阅产品类型无法显示加入购物车按钮问题

解决WooCommerce自定义产品类型无“加入购物车”按钮问题

1. 补全产品类型注册流程

你仅定义了自定义产品类,但未完成WooCommerce的产品类型关联,需添加以下代码完成注册:

关联产品类型与自定义类

add_filter( 'woocommerce_product_type_class', function( $classname, $product_type ) {
    if ( 'subscription' === $product_type ) {
        return 'WC_Product_Subscription';
    }
    return $classname;
}, 10, 2 );

后台添加产品类型选项(可选,方便创建产品时选择)

add_filter( 'product_type_selector', function( $types ) {
    $types['subscription'] = __( '订阅产品', 'your-plugin-domain' );
    return $types;
} );

2. 完善自定义产品类的核心方法

在WC_Product_Subscription类中补充关键配置与方法,确保WooCommerce识别产品可购买状态并加载按钮:

class WC_Product_Subscription extends WC_Product {

    public function __construct( $product ) {
        $this->product_type = 'subscription';
        $this->purchasable = true;
        $this->downloadable = false;
        $this->virtual = true;
        $this->sold_individually = true;
        $this->manage_stock = false;
        // 必须添加add_to_cart支持,这是显示按钮的前提
        $this->supports[] = 'add_to_cart';
        $this->supports[] = 'ajax_add_to_cart';
        parent::__construct( $product );
    }

    public function is_purchasable() {
        return true;
    }

    // 强制返回库存可用状态,避免因默认库存逻辑隐藏按钮
    public function is_in_stock() {
        return true;
    }

    public function add_to_cart_url() {
        return apply_filters( 'woocommerce_product_add_to_cart_url', get_permalink( $this->get_id() ), $this );
    }

    public function add_to_cart_text() {
        $text = $this->is_purchasable() && $this->is_in_stock() ? __( '加入购物车', 'woocommerce' ) : __( '了解更多', 'woocommerce' );
        return apply_filters( 'woocommerce_product_add_to_cart_text', $text, $this );
    }
}

3. 强制加载加购按钮模板

若以上步骤仍无效,可让自定义产品类型复用Simple产品的加购模板:

add_filter( 'woocommerce_get_template_part', function( $template, $slug, $name ) {
    // 替换订阅产品的加购模板为Simple产品模板
    if ( 'single-product/add-to-cart' === $slug && $name === 'subscription' ) {
        $template = WC()->plugin_path() . '/templates/single-product/add-to-cart/simple.php';
    }
    return $template;
}, 10, 3 );

4. 验证产品后台设置

编辑对应产品,确认产品类型已选择为「订阅产品」(若添加了步骤1的选项),保存后刷新前端产品页即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:10:15