Customizing your WooCommerce store via PHP can involve a variety of tasks, from personalizing orders to managing customer interactions. Often, you might need to find a specific customer’s information, but all you have is their email address.
For example, on this same website, I have custom contact forms that give me a name and an email address upon submit. What if I need to check if the email address is an existing WooCommerce customer who has placed some orders?
Well, the PHP below will give you a quick way to “calculate” the customer ID if you only have an email address. It’s then easy to use the result in a custom calculation or core function, such as wc_get_orders().
Enjoy!
PHP Snippet: Calculate WooCommerce Customer ID (WordPress User ID) From An Email Address
/**
* @snippet Get WooCommerce User Id From User Email
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 9
* @community https://businessbloomer.com/club/
*/
function bbloomer_get_customer_id_from_email( $email ) {
$customer = get_user_by( 'email', $email );
if ( $customer ) return $customer->ID;
return false;
}
The bbloomer_get_customer_id_from_email() function retrieves the customer ID associated with a given email address. This can be useful in various situations within a WooCommerce environment.
Assuming you have the customer’s email address stored in a variable:
$customer_email = "customer@example.com";
…you can call the function to get the customer ID and run code based on the response:
$customer_id = bbloomer_get_customer_id_from_email( $customer_email );
if ( $customer_id ) {
// Customer ID found
// do something
} else {
// Customer ID NOT found
// do something else
}
The function uses get_user_by( ’email’, $email ) to check if a customer exists with the provided email address. This function is part of WordPress and retrieves the WP_User object if a user with that email is found.