Hi everyone,

in this tutorial, we’re going to explain how to get orders ID from woocommerce by product ID.

1. Open your theme (child theme preferred) folder and open file functions.php.

2. Paste this code:

function get_orders_ids_by_product_id($product_id) {

    global $wpdb;
    $order_status = ['wc-completed', 'wc-processing', 'wc-on-hold'];
    
    $results = $wpdb->get_col("
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id' 
        AND order_item_meta.meta_value = '".$product_id."' 
        ORDER BY order_items.order_id DESC");

    return $results;
}

This function will give as all woocommerce orders IDS from a specific product.

Output:

array(
   2321,
   2322,
   2323,
   2324
)

Where we can use this?

Let’s say we want to have a list of all orders from a specific product, we easily can go through all products and get all orders.

$orders_ids = get_orders_ids_by_product_id(1003) // NOTE: Please replace product ID with a real product ID 

// now when we have all orders ids we can do somethin like bellow:

if ( !empty( $orders_ids ) ) {
    foreach ( $orders_ids as $order_id ) {
        // get order by order ID
        $order = wc_get_order($order_id);

        // do what do you want
    }
}