Skip to content

Instantly share code, notes, and snippets.

@rfmeier
Created November 7, 2017 17:21
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 rfmeier/f8945536ed42b1f0c32ac8b6b7e15f1d to your computer and use it in GitHub Desktop.
Save rfmeier/f8945536ed42b1f0c32ac8b6b7e15f1d to your computer and use it in GitHub Desktop.
Get all orders for a product in WooCommerce.
<?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