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
andAND pm.meta_key IN ( '_billing_email' )
toAND 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 yourfunctions.php
or in your child themefunctions.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