I need to set the total number of products as stock quantity in variation products and I don't know which hook to use.
I'm currently using the woocommerce_admin_process_product_object hook and I don't know if it's correct, I guess I won't be able to get out of this without help.
Also here I tried wc_update_product_stock and set_stock_quantity as functions, neither of them give any results, so I thought the hook might not be correct.
add_action( 'woocommerce_admin_process_product_object', 'set_new_variation_stock_quantity' );
function set_new_variation_stock_quantity( $product ) {
global $product;
$total = 0;
// Get variation product total quantity
if ( $product->is_type('variable') ) {
foreach ( $product->get_visible_children() as $variationId ) {
$variation = wc_get_product( $variationId );
$total += $variation->get_stock_quantity();
}
}
// Just for variation product
if ( $product->is_type( 'variable' ) ) {
// Try wc_update_product_stock function
$product = wc_update_product_stock( $product, $total, 'set', 'false' );
return $product;
// Try other set_stock_quantity
$product = $product->set_stock_quantity( $product, $total);
$product->save();
return $product;
}
return $product;
}