Created
December 29, 2017 16:38
-
-
Save lukecav/05afef12feaf980c121da9afb9291ad5 to your computer and use it in GitHub Desktop.
Get All orders IDs for a given product ID in WooCommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get All orders IDs for a given product ID. | |
* | |
* @param integer $product_id (required) | |
* @param array $order_status (optional) Default is 'wc-completed' | |
* | |
* @return array | |
*/ | |
function get_orders_ids_by_product_id( $product_id, $order_status = array( 'wc-completed' ) ){ | |
global $wpdb; | |
$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' | |
"); | |
return $results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found that
Thankyou lukecav for the query