in this example, we add two fields, one billing_phone and another phone, you can replace either one to use a custom field
/**
* Include billing phone in the WooCommerce customer search dropdown
* and display it in the results.
*
* @param array $found_customers Array of found customers.
* @return array Modified array of customers to include phone number search.
*/
function custom_woocommerce_customer_search_by_billing_phone( $found_customers ) {
global $wpdb;
// Get the search term
$term = isset( $_GET['term'] ) ? wc_clean( wp_unslash( $_GET['term'] ) ) : '';
if ( empty( $term ) ) {
return $found_customers;
}
// Query to search for users by billing phone
$phone_query = $wpdb->prepare(
"
SELECT DISTINCT user_id
FROM {$wpdb->usermeta}
WHERE meta_key = 'billing_phone'
AND meta_value LIKE %s
LIMIT 10
",
'%' . $wpdb->esc_like( $term ) . '%'
);
$user_ids = $wpdb->get_col( $phone_query );
if ( ! empty( $user_ids ) ) {
foreach ( $user_ids as $user_id ) {
$user = get_userdata( $user_id );
if ( $user ) {
// Fetch the billing phone number
$billing_phone = get_user_meta( $user_id, 'billing_phone', true );
// Construct the display string
$display_name = sprintf(
'%s (#%d – %s%s)',
esc_html( $user->display_name ),
$user->ID,
esc_html( $user->user_email ),
$billing_phone ? ' – ' . esc_html( $billing_phone ) : ''
);
// Add to the found customers list
$found_customers[ $user->ID ] = $display_name;
}
}
}
return $found_customers;
}
add_filter( 'woocommerce_json_search_found_customers', 'custom_woocommerce_customer_search_by_billing_phone' );