Add the function to your theme’s functions.php
file or a custom plugin:
function get_user_id_by_woocommerce_phone($phone_number) {
global $wpdb;
// Sanitize the phone number
$phone_number = sanitize_text_field($phone_number);
// Prepare the query to search usermeta for the phone number
$query = $wpdb->prepare(
"SELECT user_id FROM $wpdb->usermeta WHERE meta_key IN (%s, %s) AND meta_value = %s",
'billing_phone',
'shipping_phone',
$phone_number
);
// Execute the query
$user_id = $wpdb->get_var($query);
// Return the user ID or false if not found
return $user_id ? intval($user_id) : false;
}
You can call this function wherever you need to find a user ID by their phone number. Here’s an example usage:
$phone_number = '123-456-7890'; // Replace with the phone number you are searching for
$user_id = get_user_id_by_woocommerce_phone($phone_number);
if ($user_id) {
echo 'User ID is: ' . $user_id;
} else {
echo 'No user found with this phone number.';
}