This page looks best with JavaScript enabled

How to get woocommerce Customers Email by Product ID

 ·  ☕ 2 min read  ·  👽 john hashim

So you have a shop that sales different product and you would like to follow up based on products that where purchased by your customers, this is not a big deal if all you need is an email, address, name or any information you collect on your checkout form as it is all saved in your database.

This is very important if your running Google ads to try and focus on where most of your customers are based or trying to get your customers feedback.

Well, this simple snippet will help you get any information you’re trying to get in an Array form then you can extract it based on your choice.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// Access WordPress database
global $wpdb;
 
// Select Product ID
$product_id = xxx;
       
// Find billing emails in the DB order table
$statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );

$customer_emails = $wpdb->get_col("
   SELECT DISTINCT pm.meta_value FROM {$wpdb->posts} AS p
   INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id
   INNER JOIN {$wpdb->prefix}woocommerce_order_items AS i ON p.ID = i.order_id
   INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS im ON i.order_item_id = im.order_item_id
   WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $statuses ) . "' )
   AND pm.meta_key IN ( '_billing_email' )
   AND im.meta_key IN ( '_product_id', '_variation_id' )
   AND im.meta_value = $product_id
");
 
// Print array on screen
print_r( $customer_emails );
?>

incase you want to verify whether someone really purchased the product by name you would still use the same snippet but in this case, you would have to change $customer_emails

to $customer_names
and AND pm.meta_key IN ( '_billing_email' )
to AND pm.meta_key IN ( '_billing_name' )
this will make your life easier.

Where can I add this code?

If it’s your own custom theme feel free to add it in your functions.php
or in your child theme functions.php

NB: You have to test this code on your local site or staging site before running it on your production site.

feel free to let me know whats other best options or let me know if that worked out. 😉

Share on

john hashim
WRITTEN BY
john hashim
Web Developer