Skip to content

Instantly share code, notes, and snippets.

@siaeb
Created February 9, 2023 08:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siaeb/a8b04d1cee841335cd7c727c2d3ea92c to your computer and use it in GitHub Desktop.
Save siaeb/a8b04d1cee841335cd7c727c2d3ea92c to your computer and use it in GitHub Desktop.
WooCommerce Get All orders IDs for a given product ID.
/**
* 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