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

在主题函数中添加WooCommerce数量选择器时出现get_cart() on null错误

问题分析与修复方案

错误根源

报错function get_cart() on null说明你调用WC()->cart->get_cart()时,WC()->cart这个购物车对象还未被实例化。在woocommerce_loop_add_to_cart_link钩子的执行阶段,可能处于页面加载早期,或是在后台等不加载购物车的环境中,直接调用购物车方法就会触发这个错误。

具体修复步骤

1. 先判断购物车对象是否存在

如果你的代码需要读取购物车数据,必须先做存在性检查,避免对象为null时调用方法:

// 替换你原来的get_cart()调用逻辑
if ( isset( WC()->cart ) ) {
    $cart_data = WC()->cart->get_cart();
    // 后续处理购物车数据的逻辑
}

2. 简化数量输入框实现(无需依赖购物车)

如果只是要在商品循环中显示数量输入框,完全可以不调用购物车对象,直接输出HTML即可:

function custom_loop_quantity_input( $html, $product ) {
    // 仅给简单商品添加数量框,可根据需求调整商品类型
    if ( ! $product->is_type( 'simple' ) ) {
        return $html;
    }

    // 构建数量输入框HTML
    $quantity_html = sprintf(
        '<div class="loop-quantity"><input type="number" name="quantity" value="1" min="1" max="%d" step="1" class="input-text qty text" /></div>',
        $product->get_max_purchase_quantity()
    );

    // 将数量框插入到加购按钮区域
    $html = str_replace( '</a>', $quantity_html . '</a>', $html );

    return $html;
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_loop_quantity_input', 10, 2 );

3. 若需读取购物车中已有商品数量

如果要显示用户已加入购物车的该商品数量,除了判断购物车对象,还要确保当前是前台页面(后台不会加载购物车):

function custom_loop_quantity_with_cart( $html, $product ) {
    // 后台页面或购物车未初始化时,直接返回原HTML
    if ( is_admin() || ! isset( WC()->cart ) ) {
        return $html;
    }

    $product_id = $product->get_id();
    $cart_item_key = WC()->cart->generate_cart_id( $product_id );
    $cart_item = WC()->cart->get_cart_item( $cart_item_key );
    // 购物车中有该商品则取已有数量,否则默认1
    $current_qty = isset( $cart_item['quantity'] ) ? $cart_item['quantity'] : 1;

    $quantity_html = sprintf(
        '<div class="loop-quantity"><input type="number" name="quantity" value="%d" min="1" max="%d" step="1" class="input-text qty text" /></div>',
        $current_qty,
        $product->get_max_purchase_quantity()
    );

    $html = str_replace( '</a>', $quantity_html . '</a>', $html );

    return $html;
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_loop_quantity_with_cart', 10, 2 );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:10:43