我一直在尝试让小数数量在 WooCommerce 中工作,但我不知道为什么它不起作用。
我的插件代码(见下文)成功地允许输入以 0.5 为增量的小数,正如“Fabric”类别中所有产品的预期一样。到目前为止,一切都很好。它还允许以 0.5 为增量更新购物车中的数量。
但是,当我将带有小数数量的产品添加到购物车时,或者将数量更改为小数后在购物车中单击“更新”时,添加的金额无论如何都是整数。我知道这一点是因为例如添加 2.5 仍然会导致购物车中的价格总计为 2 *(并且购物车中仅显示 2 件商品)。 (此外,当我们点击数量为 2.5 的“添加到购物车”时,通知显示“已将 2 件商品添加到购物车。”)
所以在某个地方,我缺少一些设置或代码,这些设置或代码实际上选择了选择的小数数量输入而不截断它。有没有其他人有这个问题?我在网上能找到的所有内容都是下面的代码应该可以工作。
感谢您提供的任何帮助。
这是我的代码,主要基于本网站上的其他解决方案:
(我使用的是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;
}
尝试使用以下修改和简化的代码版本:
remove_filter('woocommerce_stock_amount', 'intval');
add_filter('woocommerce_stock_amount', 'floatval');
add_filter( 'woocommerce_quantity_input_args', 'filter_quantity_input_args', 10, 2 );
function filter_quantity_input_args( $args, $product ){
$product_id = $product->get_parent_id() > 0 ? $product->get_parent_id() : $product->get_id();
if ( has_term('Fabric', 'product_cat', $product_id) ) {
$args['min_value'] = 1;
$args['step'] = 0.5;
}
return $args;
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。