Am trying to set any order that has the item ( item id 1511 ) to be set as 'processing'
I tried to play around with this code in this answer, but without the desired result. I'm not sure what am doing wrong?
I tried going like this:
function action_woocommerce_order_status_changed( $order_id, $new_status, $order ) {
$items = $order->get_items();
if ( $items as $item ) {
// Get product id
$product_id = $item->get_product_id();
if ($product_id == 1511 ) {
$order->update_status( 'processing' );
break;
}
}
add_action( 'woocommerce_order_status_changed', 'action_woocommerce_order_status_changed', 10, 4 );
I appreciate any advice.
woocommerce_order_status_changed
action hook is triggered each time when order status change.
So for your question use the woocommerce_checkout_order_created
hook (that is executed, before the e-mail notifications are sent) or the woocommerce_thankyou
hook depending on your wishes.
So you get:
function action_woocommerce_checkout_order_created( $order ) {
// Already contains the correct status
if ( $order->get_status() == 'processing' ) return;
// Set variable
$found = false;
// Get order items = each product in the order
$items = $order->get_items();
foreach ( $items as $item ) {
// Get product id
$product_id = $item->get_product_id();
if ( $product_id == 1511 ) {
$found = true;
// true, break loop
break;
}
}
// True
if ( $found ) {
$order->update_status( 'processing' );
}
}
add_action( 'woocommerce_checkout_order_created', 'action_woocommerce_checkout_order_created', 10, 1 );
OR
function action_woocommerce_thankyou( $order_id ) {
// Get order
$order = wc_get_order( $order_id );
// Already contains the correct status
if ( $order->get_status() == 'processing' ) return;
// Set variable
$found = false;
// Get order items = each product in the order
$items = $order->get_items();
foreach ( $items as $item ) {
// Get product id
$product_id = $item->get_product_id();
if ( $product_id == 1511 ) {
$found = true;
// true, break loop
break;
}
}
// True
if ( $found ) {
$order->update_status( 'processing' );
}
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );