Woocomerce - Update max quantity for product variation

Viewed 263

I'm trying to update max quantity for all variations of my variable product to ie 345.

$available_variations = $product->get_available_variations();


foreach ($available_variations as $variation) 
{ 
$variation_ID = $variation->ID;
update_post_meta( $variation_ID , 'max_qty', 345 );

}

It doesn't happen.

2 Answers

You are not using the correct way to get the variation ID and the product meta key max_qty doesn't exist in WooCommerce database on wp_postmeta table for product_variation post type.

Instead you can use the following filter hook to set a specific maximum quantity to product variations:

add_filter( 'woocommerce_available_variation', 'wc_available_variation_max_qty', 10, 3 );
function wc_available_variation_max_qty( $data, $product, $variation ) {
    $data['max_qty'] = 345;

    return $data;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Why not set it to 345 by default?

$max_m = $max_l = $max_xl = $max_xxl = $max_xxxl = '345';

if($max_qty != 345){
   //Limit Reached error
}

OR

$product->get_available_variations = '345';
if($variation_ID != 345){
    $variation_ID->max_qty = 345;
}

Since it's an online shop why not use MySQLi? It's PHP powered so why not? this way you can do MySQLi->query, and UPDATE the value.

Edited

Related