I'm currently working on an automated status changes for WooCommerce orders: When a product stock reaches 50%, I am trying to change all related "processing" orders to 'kundenupdate' order status.
I am using the function retrieve_orders_ids_from_a_product_id()
from this answer thread, querying orders with "processing" status, form a product ID in the code below:
function retrieve_orders_ids_from_a_product_id( $product_id ) {
global $wpdb;
// Define HERE the orders status for queried orders
$orders_statuses = "'processing'";
# Requesting All defined statuses Orders IDs for a defined product ID
return $wpdb->get_col( "
SELECT DISTINCT woi.order_id
FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p
WHERE woi.order_item_id = woim.order_item_id
AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses )
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value LIKE '$product_id'
ORDER BY woi.order_item_id DESC"
);
}
/**
* Automated order status changes
*/
add_action('woocommerce_order_status_changed', 'woocommerce_auto_processing_orders');
function woocommerce_auto_processing_orders( $order_id ) {
if ( ! $order_id )
return;
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
//product_id gets tracked automatically
$product = wc_get_product( $item['product_id'] );
$product_id = $item->get_product_id();
$orders_ids_array = retrieve_orders_ids_from_a_product_id( $product_id );
$stock = $product->get_stock_quantity();
//If order is "processing".
foreach ( $orders_ids_array as $order_id_array ) {
if( $order_id_array->has_status( 'processing' ) ) {
if( $stock == 350 ) {
$order_id_array->update_status( 'kundenupdate' );
} elseif( $stock == 140 ) {
$order_id_array->update_status('on-hold');
}
}
}
}
}
If I change the code for only one order, it works. But if I try to get all orders for a specific product_id, which all are in the state 'processing', it doesn't work.
I also don't know, if the function retrieve_orders_ids_from_a_product_id()
is working correctly, since I don't know, how to debug it in php.
How do I get a correct array of all orders for a specific product_id, which all are in the state 'processing'?