How do I change the initial quantity of a product in woocommerce?

By default, the product quantity is always "1" when viewing a product page. There doesn't seem an out-of-the-box option to set a different quantity value upon visit, and I don't know what hook or function to look for.

Your help is appreciated.

Topic woocommerce-offtopic plugin-development hooks Wordpress

Category Web


There is a beautiful example in WooCommerce docs
the example even includes a conditional amount.

/**
 * Adjust the quantity input values
 */
add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products

function jk_woocommerce_quantity_input_args( $args, $product ) {
    if ( is_singular( 'product' ) ) {
        $args['input_value']    = 2;    // Starting value (we only want to affect product pages, not cart)
    }
    $args['max_value']  = 80;   // Maximum value
    $args['min_value']  = 2;    // Minimum value
    $args['step']       = 2;    // Quantity steps
    return $args;
}

Ref: https://woocommerce.com/document/adjust-the-quantity-input-values/

what you really need to set is the 'input_value' (meaning quantity) value. you have to change the min / max value or step values.. those control the actually input values.


Using this code you can easy to set update quantity . qty box. i was also try this method it's working fine for me ...I hope it's also helpful thank you :)

function wpse_292293_quantity_input_default( $args, $product ) {


$productID = $product->id;

foreach( WC()->cart->get_cart() as $key => $item ){
    
    if( $item['product_id'] == $productID ){    
        $args['input_value'] = $item['quantity'];   
        return $args;       
    }
    
} 

$args['input_value'] = 1;
return $args;

}
 add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );

You can use the woocommerce_quantity_input_args filter:

function wpse_292293_quantity_input_default( $args, $product ) {
    $args['input_value'] = 2;

    return $args;
}
add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );

When the quantity input is output, it's output with the woocommerce_quantity_input() function. This function accepts several arguments including the default value for the input. This filter lets you replace values in the arguments across all uses of the function.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.