Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cyberwani
Forked from lukecav/functions.php
Created August 17, 2019 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyberwani/3c02f05f1177187aafac87a92c52d2d4 to your computer and use it in GitHub Desktop.
Save cyberwani/3c02f05f1177187aafac87a92c52d2d4 to your computer and use it in GitHub Desktop.
Get All orders IDs for a given product ID in WooCommerce
/**
* 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;
}
/*
* References
* https://docs.woocommerce.com/wc-apidocs/function-wc_get_orders.html
* https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query
* https://stackoverflow.com/questions/45848249/woocommerce-get-all-orders-for-a-product
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment