For a Woocommerce store that allows backorders (customers can purchase items that currently have no stock), with time as physical and store stocks are updated, there is no way to finally tell when an older order eventually has all the missing components (the products that were backordered, and that are now in stock) and is finally ready to be packed.
Due to this: The objective is to frequently check/query/loop through all orders with order status "Processing" and check what is the current status of each of their items and if all items are in stock (So there are no items that have current stock status on backorder), then it will update this order with a custom ACF field 'Ready to Pack'
This attempt is initially based on Auto completed status for all existing processing orders in WooCommerce and also has a bit of Change order status when order has backorder items in it
function auto_update_orders_internal_status(){
// Get all current "processing" customer orders
$processing_orders = wc_get_orders( $args = array(
'numberposts' => -1,
'post_status' => 'wc-processing',
) );
if(!empty($processing_orders))
foreach($processing_orders as $order) {
// Iterating through each item in the order
foreach ( $order->get_items() as $item ) {
// Get a an instance of product object related to the order item
$product = $item->get_product();
// Check if the products are currently in stock
if( $product->is_in_stock() ){
// Update custom field 'Ready to Pack'
add_action('acf/save_post', 'update_internal_status_ready_to_pack');
}}
}
}
//Run check function when an order status is change to completed
add_action( 'woocommerce_order_status_completed', 'auto_update_orders_internal_status' );
//Save ACF field function
function update_internal_status_ready_to_pack ( $order_id ) {
$internalstatus = 'Ready to Pack';
update_field( 'internal_status', $internalstatus, $order_id );
}
One thing I am aware I don't fully grasp here is the method of , after getting all orders on "Processing status", successfully checking each order the stock status of their corresponding items