I have a variable product on WooCommerce with 2 variations
The variations are based on weight. One of them is 0.5 kg and the other one is 1 kg.
So I would like to change default quantify selector value and set the selector value based on selection on variation. For example, When user select variation 0.5 kg variation the quantify selector value start as 0.5 and when select 1 kg variation start as 1.
I have changed this code, but it is not working and when user click on 0.5 first the 0.5 appear on input quantity field, but it’s not increased 0.5 by 0.5.
Any help is appreciated.
Here is my code:
function enqueue_custom_scripts() {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom-script.js', array( 'jquery' ), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_scripts' );
And my js code is:
(function($) {
// Wait for the variation to be selected
$(document).on('found_variation', function(event, variation) {
// Get the selected variation weight
var variationWeight = parseFloat(variation.weight);
// Update the default quantity selector value based on the selected variation weight
$('input[name="quantity"]').val(variationWeight);
// Trigger a change event on the quantity selector to update the displayed value
$('input[name="quantity"]').trigger('change');
});
})(jQuery);
2
Answers
I've found the solution and hope will be useful for everyone who might have a problem like me.
This is based on your initial question content (that you changed multiple times).
There is a much simpler approach, that will be easier and more integrated in default WooCommerce, using product variation weight as quantity step (and min quantity). The following code will also handle the quantity input field in cart.
I have simplified the quantity step calculation in this code (if you need, you will be able easily to make your calculation in the first function).
Important:
The code:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.