基于WooCommerce产品类别的自定义小数数量输入异常求助
问题
在WooCommerce中实现小数数量功能时遇到问题:编写的插件代码已让“Fabric”类别产品的数量输入支持0.5增量,购物车中也能按此步长修改数量,但添加小数数量(如2.5)到购物车或更新时,实际添加的却是整数,总价按整数计算,提示也显示添加了整数数量。使用WordPress 6.5.2,现有代码如下:
// Removes the WooCommerce filter, that is validating the quantity to be an int remove_filter('woocommerce_stock_amount', 'intval'); // Add a filter, that validates the quantity to be a float add_filter('woocommerce_stock_amount', 'floatval'); // Add min value to the quantity field (default = 1) add_filter('woocommerce_quantity_input_min', 'min_decimal'); function min_decimal($val) { return 1; } // Add step value to the quantity field (default = 1) add_filter('woocommerce_quantity_input_step', 'step_decimal', 10, 2); function step_decimal($val, $product) { $product_id = $product->get_id(); if (has_term('Fabric','product_cat', $product_id)) { return 0.5; } return 1.0; }
请问哪里遗漏了设置或代码,能让小数数量不被截断?
解决方案
你漏了几个关键的WooCommerce过滤钩子,这些钩子会在添加/更新购物车、保存订单时强制将数量转为整数,补充以下代码即可解决问题:
- 允许小数数量通过添加购物车验证
WooCommerce默认会验证数量是否为整数,需要通过woocommerce_add_to_cart_validation过滤器放行Fabric类产品的小数数量:
add_filter('woocommerce_add_to_cart_validation', 'allow_decimal_cart_qty', 10, 3); function allow_decimal_cart_qty($passed, $product_id, $quantity) { if (has_term('Fabric', 'product_cat', $product_id)) { $passed = true; } return $passed; }
- 保留购物车更新时的小数数量
更新购物车时系统会自动把数量转成整数,用woocommerce_update_cart_action_cart_item_quantity过滤器强制转为浮点数:
add_filter('woocommerce_update_cart_action_cart_item_quantity', 'keep_decimal_qty_on_cart_update', 10, 4); function keep_decimal_qty_on_cart_update($quantity, $cart_item_key, $cart_item, $cart) { if (has_term('Fabric', 'product_cat', $cart_item['product_id'])) { $quantity = floatval($quantity); } return $quantity; }
- 正确显示购物车中的小数数量
确保购物车页面能正确展示小数数量,避免被格式化掉:
add_filter('woocommerce_cart_item_quantity', 'display_decimal_cart_qty', 10, 3); function display_decimal_cart_qty($quantity_html, $cart_item, $cart_item_key) { if (has_term('Fabric', 'product_cat', $cart_item['product_id'])) { $quantity = wc_format_decimal($cart_item['quantity']); $price = wc_price($cart_item['data']->get_price()); $quantity_html = "<span class='quantity'>{$quantity} × {$price}</span>"; } return $quantity_html; }
- 确保订单保存时不截断小数数量
订单生成时需要强制保留小数数量,避免被转成整数:
add_action('woocommerce_new_order_item', 'save_decimal_order_qty', 10, 3); function save_decimal_order_qty($item_id, $item, $order_id) { if ($item->get_type() === 'line_item' && has_term('Fabric', 'product_cat', $item->get_product_id())) { $item->set_quantity(floatval($item->get_quantity())); $item->save(); } }
将以上代码补充到你的插件中,Fabric类产品就能完整支持0.5增量的小数数量,添加、更新购物车时不会再截断小数,总价也会按实际数量计算。
内容的提问来源于stack exchange,提问作者Venk Reddy
相关产品推荐
相关产品推荐

