I have been trying to get decimal quantities to work in WooCommerce, and I am at a loss for why it’s not working.
My plugin code (see below) successfully allows the inputs to be decimals in 0.5 increments as expected for all products in the "Fabric" category. So far, so good. It also allows quantity updates in the cart to be done as 0.5 increments.
However, when I add a product with a fractional quantity to the cart or when I click Update in the cart after changing the quantity to a fractional number, the amount added is an integer anyway. I know this because adding 2.5, for example, still results in a total of 2 * price in the cart (as well as displaying only 2 items in the cart). (Also, when we click "Add to Cart" with the 2.5 quantity, the notice says "Added 2 items to cart.")
So somewhere, I am missing some setting or code that actually takes the fractional quantity input being selected without truncating it. Has anyone else had this problem? Everything I can find online is that the code below should work.
Thanks for any help you can provide.
Here is my code, largely based on other solutions on this site:
(I’m using 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;
}
2
Answers
Closing the loop: The original code was correct, though not as streamlined as the first suggested solution. Moving the code from a plugin functions.php to the child theme functions.php did the trick. Not sure why, but if it helps someone else, that was the ultimate solution to the problem I was having.
Try the following revised and simplified code version instead:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.