Skip to content

Instantly share code, notes, and snippets.

@iMojtaba
Created January 15, 2017 05:53
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 iMojtaba/7da33e7f4435c631246b72b90419901c to your computer and use it in GitHub Desktop.
Save iMojtaba/7da33e7f4435c631246b72b90419901c to your computer and use it in GitHub Desktop.
Get customers that bought a product in woocommerce
function get_customers_bought_product ( $product_id ) {
global $wpdb;
return $wpdb->get_results(
$wpdb->prepare( "
SELECT postmeta.meta_value as email
FROM {$wpdb->prefix}woocommerce_order_items as order_items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON order_items.order_item_id = itemmeta.order_item_id
LEFT JOIN {$wpdb->postmeta} AS postmeta ON order_items.order_id = postmeta.post_id
LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
WHERE
posts.post_status IN ( 'wc-completed', 'wc-processing' ) AND
itemmeta.meta_value = %s AND
itemmeta.meta_key IN ( '_variation_id', '_product_id' ) AND
postmeta.meta_key IN ( '_billing_email' )
GROUP BY postmeta.meta_value
", $product_id
),
ARRAY_A
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment