I use following code to re save the product variations, when there is a paid order on it, but nothing happen
add_action('woocommerce_payment_complete', 'refresh_zero_stock');
function refresh_zero_stock($order_id){
$order = new WC_Order( $order_id );
foreach ($order->get_items() as $item_key => $item ){
$item_quantity = $item->get_quantity();
if($item_quantity == 0){
$product_id = $item->get_product_id();
$product_data = wc_get_product($product_id);
if ($product_data->is_type('variable')){
$handle = new WC_Product_Variable($product_id);
$variations1=$handle->get_children();
foreach ($variations1 as $value) {
$single_variation=new WC_Product_Variation($value);
$single_variation->save();
}
}
}
}
}
what is the problem with this action hook? please help.
3
Answers
I find the problem. I have to add
before
The hook is not the problem… The main problem is
if( $item->get_quantity() == 0 ){
that is alwaysfalse
, where$item->get_quantity()
need to be replaced with the product stock quantity instead. Try the following:Code goes in functions.php file of the active child theme (or active theme). It should better works.
As the hook
woocommerce_payment_complete
doesn’t seems to work, try the following instead based on order status change (Note: this code will run only once for each order):Code goes in functions.php file of the active child theme (or active theme). It could better works.