Created
November 7, 2017 17:21
-
-
Save rfmeier/f8945536ed42b1f0c32ac8b6b7e15f1d to your computer and use it in GitHub Desktop.
Get all orders for a product in WooCommerce.
This file contains 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
<?php | |
/** | |
* Get all orders given a product. | |
* | |
* @param integer $product_id The product ID. | |
* | |
* @return array An array of WC_Order objects. | |
*/ | |
function rfm_get_orders_by_product( $product_id ) { | |
global $wpdb; | |
$raw = " | |
SELECT | |
`items`.`order_id`, | |
MAX(CASE WHEN `itemmeta`.`meta_key` = '_product_id' THEN `itemmeta`.`meta_value` END) AS `product_id` | |
FROM | |
`{$wpdb->prefix}woocommerce_order_items` AS `items` | |
INNER JOIN | |
`{$wpdb->prefix}woocommerce_order_itemmeta` AS `itemmeta` | |
ON | |
`items`.`order_item_id` = `itemmeta`.`order_item_id` | |
WHERE | |
`items`.`order_item_type` IN('line_item') | |
AND | |
`itemmeta`.`meta_key` IN('_product_id') | |
GROUP BY | |
`items`.`order_item_id` | |
HAVING | |
`product_id` = %d"; | |
$sql = $wpdb->prepare( $raw, $product_id ); | |
return array_map(function ($data) { | |
return wc_get_order( $data->order_id ); | |
}, $wpdb->get_results( $sql ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment