基于商品重量设置WooCommerce简单商品的数量选择器步长值
问题:WooCommerce简单商品数量选择器适配小数重量失效
需求:让WooCommerce中简单商品的数量选择器,完全匹配「配送>商品重量」里设置的数值——重量设为0.5kg时,数量选择器的起始值、步长都设为0.5;重量设为1kg时则对应1。但目前使用的代码对小于1的重量值(比如0.5)完全不起作用,原代码如下:
/*Quantity Selector Based On Simple*/ function custom_quantity_selector_min_value( $min, $product ) { $weight = $product->get_weight(); if ( $weight > 0 ) { $min = $weight; } return $min; } add_filter( 'woocommerce_quantity_input_min', 'custom_quantity_selector_min_value', 10, 2 ); //Modify the quantity selector step value. function custom_quantity_selector_step( $step, $product ) { $weight = $product->get_weight(); if ( $weight > 0 ) { $step = $weight; } return $step; } add_filter( 'woocommerce_quantity_input_step', 'custom_quantity_selector_step', 10, 2 ); //Update the quantity selector value dynamically. function custom_quantity_selector_value( $input_value, $product ) { $weight = $product->get_weight(); if ( $weight > 0 ) { $input_value = $weight; } return $input_value; } add_filter( 'woocommerce_quantity_input_value', 'custom_quantity_selector_value', 10, 2 );

解决方案
问题核心是$product->get_weight()返回的是字符串类型,当重量为小数(如0.5)时,直接赋值会导致WooCommerce处理数值时出现类型转换错误,同时默认逻辑可能强制数量为整数。修正方案如下:
- 将重量值转为浮点数,确保数值类型正确
- 提高钩子优先级,避免被其他逻辑覆盖
- 增加数值有效性校验
修正后的代码:
/* 适配商品重量的数量选择器设置 */ function custom_quantity_selector_min_value( $min, $product ) { // 获取商品重量并转为浮点数 $weight = (float) $product->get_weight(); // 仅当重量大于0时生效 if ( $weight > 0 ) { $min = $weight; } return $min; } // 提高优先级到20,确保覆盖默认逻辑 add_filter( 'woocommerce_quantity_input_min', 'custom_quantity_selector_min_value', 20, 2 ); /* 修改数量选择器步长 */ function custom_quantity_selector_step( $step, $product ) { $weight = (float) $product->get_weight(); if ( $weight > 0 ) { $step = $weight; } return $step; } add_filter( 'woocommerce_quantity_input_step', 'custom_quantity_selector_step', 20, 2 ); /* 设置数量选择器默认值 */ function custom_quantity_selector_value( $input_value, $product ) { $weight = (float) $product->get_weight(); if ( $weight > 0 ) { $input_value = $weight; } return $input_value; } add_filter( 'woocommerce_quantity_input_value', 'custom_quantity_selector_value', 20, 2 );
额外注意事项:
- 确认WooCommerce设置>配送>配送选项中的重量单位配置正确
- 如果前端仍无法显示小数步长,检查主题是否重写了数量输入模板,需确保模板中
<input>标签的step属性正确输出动态值
内容的提问来源于stack exchange,提问作者MohsenJames Amra
相关产品推荐
相关产品推荐

