I have setup custom quantity inputs for simple products, which works as intended, but it breaks on variable products, so I want to get it to work on each variation of a variable product, but I can't figure out how
Simple product code:
add_filter( 'woocommerce_quantity_input_args', 'productQuantityInputArgs', 10, 2);
function productQuantityInputArgs( $args, $product ) {
if ( ! is_cart() ) {
$product = wc_get_product();
$customPasirinkimoKiekis = $product->get_meta('_quantity_product_in_package');
$stock = $product->get_meta('_stock_quantity');
$productType = $product->get_type();
if($productType === 'simple') {
$args['max_value'] = $stock - ($stock % $customPasirinkimoKiekis);
$args['input_value'] = $customPasirinkimoKiekis;
$args['min_value'] = $customPasirinkimoKiekis;
$args['step'] = $customPasirinkimoKiekis;
}
}
return $args;
}
Removing the if type === 'simple' breaks variable product pages, but each variation of product has the same needed meta data as simple products and I can't figure out how to do it for variable/variations of products
To handle all product types based on a custom field that changes product quantity input arguments, you need something more complete.
Replace all your related code with the following:
// For ajax add to cart
add_filter( 'woocommerce_loop_add_to_cart_args', 'loop_ajax_add_to_cart_quantity_fix', 10, 2 );
function loop_ajax_add_to_cart_quantity_fix( $args, $product ) {
if ( $custom_qty = $product->get_meta('_quantity_product_in_package') ) {
$args['quantity'] = $custom_qty;
}
return $args;
}
// For Single products and Cart pages
add_filter( 'woocommerce_quantity_input_args', 'filter_product_quantity_input_args', 10, 2);
function filter_product_quantity_input_args( $args, $product ) {
if ( $custom_qty = $product->get_meta('_quantity_product_in_package') ) {
$stock_qty = $product->get_stock_quantity();
if ( ! is_cart() ) {
$args['input_value'] = $custom_qty;
}
$args['min_value'] = $custom_qty;
$args['max_value'] = $stock_qty - ($stock_qty % $custom_qty);
$args['step'] = $custom_qty;
}
return $args;
}
// Variable products (Selected product variation)
add_filter( 'woocommerce_available_variation', 'filter_selected_variation_quantity_input_args', 10, 3 );
function filter_selected_variation_quantity_input_args( $data, $product, $variation ) {
if ( $custom_qty = $product->get_meta('_quantity_product_in_package') ) {
$stock_qty = $variation->get_stock_quantity();
$data['min_qty'] = $custom_qty;
$data['max_qty'] = $stock_qty - ($stock_qty % $custom_qty);
}
return $data;
}
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.