We sell handmade products. Only one variation of a variable product is purchasable.
When a variation is ordered, the stock of that variable product goes to 0 and the product cannot be ordered until the order is completed. I can set the instock status and the stock quantity as follows:
//when order is completed the stock and stock status are reset to instock and 1
add_action( 'woocommerce_order_status_completed', 'my_function' );
function my_function($order_id) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
$product_id;
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
} //end foreach
$new_stock_status = 'instock';
// 1. Updating the stock quantity
update_post_meta($product_id, '_stock', 1);
// 2. Updating the stock quantity
update_post_meta( $product_id, '_stock_status', wc_clean( $new_stock_status ) );
// 3. Updating post term relationship
wp_set_post_terms( $product_id, 'outofstock', 'product_visibility', true );
// And finally (optionally if needed)
wc_delete_product_transients( $product_id ); // Clear/refresh the variation cache
}
I am not sure whether this code is correct, but it seems to be working.
However, the single product page persists in showing the out of stock message. Only when I add:
//reset stock in product
add_action( 'woocommerce_admin_process_product_object', 'lumi_reset_stock' );
function lumi_reset_stock( $product ) {
// Using WC setters
$product->set_manage_stock(true);
$product->set_stock_quantity(1);
$product->set_stock_status('instock');
}
And save the product in the admin backend, then the product is purchasable again.
This is a bit complicated. How can i also reset the stock and stock_status for a product when an order is completed?
Looking at the database > wp_wc_product_meta_lookup the stock-status shows outofstock and the quantity is 0, even after saving the product. Do i have to reset these values?