query orders by products woocommerce

Solutions on MaxInterview for query orders by products woocommerce by the best coders in the world

showing results for - "query orders by products woocommerce"
Emilie
20 Nov 2019
1/**
2 * Get All orders IDs for a given product ID.
3 *
4 * @param  integer  $product_id (required)
5 * @param  array    $order_status (optional) Default is 'wc-completed'
6 *
7 * @return array
8 */
9function get_orders_ids_by_product_id( $product_id, $order_status = array( 'wc-completed' ) ){
10    global $wpdb;
11
12    $results = $wpdb->get_col("
13        SELECT order_items.order_id
14        FROM {$wpdb->prefix}woocommerce_order_items as order_items
15        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
16        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
17        WHERE posts.post_type = 'shop_order'
18        AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
19        AND order_items.order_item_type = 'line_item'
20        AND order_item_meta.meta_key = '_product_id'
21        AND order_item_meta.meta_value = '$product_id'
22    ");
23
24    return $results;
25}
26