Iterating through order items is a heavier process, than making a much more lighter SQL query.
Here is a custom conditional function that will check for products Ids in a Woocommerce Order (returning true or false):
function order_has_products( $order_id, $product_ids ){
$product_ids = implode( "','", $product_ids );
global $wpdb;
$result = $wpdb->get_var( "
SELECT COUNT(woim.meta_value) FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim
INNER JOIN {$wpdb->prefix}woocommerce_order_items as woi ON woi.order_item_id = woim.order_item_id
WHERE woi.order_id = $order_id AND woim.meta_key IN ('_product_id','_variation_id')
AND woim.meta_value IN ('$product_ids')
" );
return $result > 0 ? true : false;
}
Then you will use it in this way:
add_action('woocommerce_thankyou', 'wc_auto_complete_order', 20, 1);
function wc_auto_complete_order($order_id){
if (!$order_id) return;
// HERE define your Product Ids to exclude in the array
$product_ids = array( 37, 53 );
// Get an instance of the WC_Product object
$order = wc_get_order($order_id);
$found = order_has_products( $order_id, $product_ids );
if ( in_array( $order->get_payment_method(), array('cod', 'cheque', '') ) || $found ) {
return;
}
else {
$order->update_status('completed');
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
WooCommerce: Auto complete paid Orders (depending on Payment methods)