WooCommerce商品自定义库存状态显示问题求助
WooCommerce自定义库存状态显示解决方案
问题分析
原代码存在三个核心问题:
- 未区分「启用库存管理」和「仅设置有货状态」的场景,导致未填数量的有货商品被误判为缺货
- 库存数量判断逻辑有漏洞,19、20件库存会走到默认分支,无法显示实际数量
- 未处理带变体的可变商品,变体库存状态判断不准确
修正后的代码
add_filter('woocommerce_get_stock_html', function($html, $product) { // 处理带变体的可变商品 if ($product->is_type('variable')) { $has_in_stock = false; $total_stock = 0; $has_managed_stock = false; foreach ($product->get_available_variations() as $variation) { $variation_product = wc_get_product($variation['variation_id']); if ($variation_product->managing_stock()) { $has_managed_stock = true; $stock_qty = $variation_product->get_stock_quantity(); $total_stock += $stock_qty; if ($stock_qty > 0) { $has_in_stock = true; } } else { // 变体未启用库存管理,视为有货 $has_in_stock = true; } } if (!$has_in_stock) { $new_html = __('缺货', 'txtdomain'); } else if (!$has_managed_stock) { // 所有变体均未启用库存管理,显示「超过20」 $new_html = __('超过20', 'txtdomain'); } else { $new_html = $total_stock > 20 ? __('超过20', 'txtdomain') : sprintf(__('%d 件库存', 'txtdomain'), $total_stock); } } else { // 处理简单商品/单个变体商品 $manage_stock = $product->managing_stock(); $current_stock = $product->get_stock_quantity(); if (!$manage_stock) { $new_html = $product->is_in_stock() ? __('超过20', 'txtdomain') : __('缺货', 'txtdomain'); } else { if ($current_stock <= 0) { $new_html = __('缺货', 'txtdomain'); } else { $new_html = $current_stock > 20 ? __('超过20', 'txtdomain') : sprintf(__('%d 件库存', 'txtdomain'), $current_stock); } } } return sprintf('<p class="stock">%s</p>', $new_html); }, 10, 2);
代码说明
- 可变商品处理:遍历所有变体,汇总库存数量,判断是否有变体启用库存管理,统一计算整体库存状态
- 库存管理状态判断:通过
managing_stock()区分是否设置了具体库存数量,未启用时直接根据商品有货状态显示「超过20」 - 库存数量逻辑修正:
- 库存≤0:显示「缺货」
- 库存≤20:显示实际数量
- 库存>20或未设置具体数量:显示「超过20」
内容的提问来源于stack exchange,提问作者Åsa
相关产品推荐
相关产品推荐

