如何在WooCommerce的get_refreshed_fragments中支持小数数量?
解决WooCommerce购物车小数数量更新后变回整数的问题
你的代码已经完成了前端数量输入的基础设置,但WooCommerce在购物车更新的后端验证和Ajax片段渲染环节仍有强制整数的逻辑,需要补充代码覆盖这两处限制:
1. 允许购物车项保存小数数量
WooCommerce默认会验证购物车数量是否为整数,通过以下过滤器跳过该验证,允许小数数量通过:
// 允许购物车项使用小数数量 add_filter('woocommerce_validate_cart_item_quantity', 'allow_decimal_cart_quantity', 10, 4); function allow_decimal_cart_quantity($passed, $product_id, $quantity, $args) { // 仅验证数值合法性,允许正数小数 if (is_numeric($quantity) && $quantity > 0) { return true; } return $passed; }
2. 修复Ajax刷新时的数量字段渲染
点击"更新购物车"后,Ajax返回的购物车片段会重新生成数量输入框,需要确保渲染时保留小数格式:
// 确保购物车片段中的数量字段保留小数 add_filter('woocommerce_cart_item_quantity', 'render_decimal_quantity_in_cart', 10, 3); function render_decimal_quantity_in_cart($quantity_html, $cart_item_key, $cart_item) { $product = $cart_item['data']; $args = array( 'input_name' => "cart[{$cart_item_key}][qty]", 'input_value' => wc_format_decimal($cart_item['quantity'], wc_get_price_decimals()), 'max_value' => $product->get_max_purchase_quantity(), 'min_value' => 0.01, // 与步长保持一致,避免输入冲突 'step' => 0.01, // 对应你设置的小数步长 'product_name' => $product->get_name(), ); return woocommerce_quantity_input($args, $product, false); }
整合完整代码
将原有代码与新增代码合并,添加到主题的functions.php文件中:
function customize_quantity_field() { // 设置数量字段最小值 add_filter('woocommerce_quantity_input_min', 'min_decimal'); function min_decimal($val) { return 0.01; // 建议与步长统一,支持更小的小数输入 } // 设置数量字段步长 add_filter('woocommerce_quantity_input_step', 'nsk_allow_decimal'); function nsk_allow_decimal($val) { return 0.01; } // 移除整数库存验证,改用浮点数验证 remove_filter('woocommerce_stock_amount', 'intval'); add_filter('woocommerce_stock_amount', 'floatval'); } add_action('wp', 'customize_quantity_field'); // 允许购物车项使用小数数量 add_filter('woocommerce_validate_cart_item_quantity', 'allow_decimal_cart_quantity', 10, 4); function allow_decimal_cart_quantity($passed, $product_id, $quantity, $args) { if (is_numeric($quantity) && $quantity > 0) { return true; } return $passed; } // 确保购物车片段中的数量字段保留小数 add_filter('woocommerce_cart_item_quantity', 'render_decimal_quantity_in_cart', 10, 3); function render_decimal_quantity_in_cart($quantity_html, $cart_item_key, $cart_item) { $product = $cart_item['data']; $args = array( 'input_name' => "cart[{$cart_item_key}][qty]", 'input_value' => wc_format_decimal($cart_item['quantity'], wc_get_price_decimals()), 'max_value' => $product->get_max_purchase_quantity(), 'min_value' => 0.01, 'step' => 0.01, 'product_name' => $product->get_name(), ); return woocommerce_quantity_input($args, $product, false); }
额外说明
- 价格计算会自动基于小数数量执行,WooCommerce核心逻辑是
单价 × 数量,只要数量为浮点数就会生成正确的总价。 - 若商品按重量、体积等单位计价,需确保商品单价设置为对应单位的价格(例如每0.01千克的价格)。
内容的提问来源于stack exchange,提问作者Zorro
相关产品推荐
相关产品推荐

