Created
February 9, 2023 08:10
-
-
Save siaeb/a8b04d1cee841335cd7c727c2d3ea92c to your computer and use it in GitHub Desktop.
WooCommerce Get All orders IDs for a given product ID.
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 | |
*/ | |
public function getOrderIdsByProductId($product_id, $order_status = ['wc-completed', 'wc-processing']) { | |
global $wpdb; | |
$query = " | |
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 $wpdb->get_col($query); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment