Hi,
in an attempt to give back to the community, here is code I wrote, that takes care to update a parent product stock to the sum of all its variations’ stock anytime a product is updated.
(This allows the code to work even stock is set from third-party stock editing plugins such as Woocommerce Stock Manager which I tested.)
//TMI
// IF the currently edited product has variations AND does manage stock at product level
// THEN Populate product stock as the sum of all variations stock
// Hook on the "product was updated" Woocommerce hook
add_action( 'woocommerce_update_product', 'tmi_update_stocks_on_product_save', 10, 1 );
// Do our magic on the product stock level
function tmi_update_stocks_on_product_save ( $product_id ) {
//BugFu::log('tmi_update_stocks_on_product_save: '.$product_id);
// get the product object
$product = wc_get_product( $product_id );
// product stock is not managed (manually)
// if it is not managed then the DB stock entry is /null/ and will not change anyway
if (! $product->get_manage_stock()) { return; }
// prepare final stock value
$total_stock_quantity = 0;
// fetch all variations of the product
$this_product_variations_IDs = $product->get_children();
if (! $this_product_variations_IDs )
{
// if no variations, no stock
$total_stock_quantity = 0;
}
else
{
foreach ($this_product_variations_IDs as $the_variation_ID)
{
$the_variation = wc_get_product( $the_variation_ID );
// increment the product stock with this variation's stock
$total_stock_quantity += $the_variation->get_stock_quantity();
}
}
// Finally update the product stock
// side-effect : error message on product save IF only variation stock was set AND product was not reloaded
// because then the product stock in the form has become different from the stock in DB
$product->set_stock_quantity($total_stock_quantity);
// Unregister our hook to avoid recursive infinite loop
remove_action( 'woocommerce_update_product', 'tmi_update_stocks_on_product_save', 10, 1 );
$product->save();
// Register our hook back
add_action( 'woocommerce_update_product', 'tmi_update_stocks_on_product_save', 10, 1 );
}
//end TMI
————
Side note : having dug somewhat into these things, I do not see anywhere where
WooCommerce itself will count the largest variation stock level
.
If the “manage product at stock level” is checked, then it will return the set stock. If it is unchecked, it won’t make any attempt (that I saw) to retrieve any stock value, which corresponds to the DB entry where _stock is of null value.
HTH
Thierry