Change input quantity step value of simple product based on weight in WooCommerce
P粉351138462
2023-09-04 21:55:45
<p>I want the quantity selector value to change based on the weight we set in Shipping >Product Weight for a simple product.
As shown in the image below, when we set the weight of the product to 0.5 kg, the product quantity selector starts from 0.5 and if we set it to 1 kg, it starts from 1. Finally when we set the weight to each number, the quantity selector should fire based on the weight number we defined.
I modified the code but it doesn't work for values less than 1. </p>
<pre class="brush:php;toolbar:false;">/*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 );</pre></p>
Correct code substitutions to use (Update):
It will work smoothly as expected:
Please make sure you also add (for inventory management):
The code is located in the functions.php file of the active child theme (or active theme). Tested and works.
When loading a page containing a product of
0.5
weight:Set the correct quantity input on the product and increase
in steps of
0.5 (normal steps are also 1) .On the cart page, everything works as expected with a step size of
0.5
(normal step size is also 1).Related (for variations): Change input quantity step value based on selected variation weight in WooCommerce