Woocommerce: Search customers in ajax based on billing phone num

in this example, we add two fields, one billing_phone and another phone, you can replace either one to use a custom field

    
/** * Include phone number and billing phone number 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_phone_with_display( $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 phone number and billing phone number $phone_query = $wpdb->prepare( " SELECT DISTINCT user_id FROM {$wpdb->usermeta} WHERE (meta_key = 'billing_phone' OR meta_key = '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 phone number from the user's meta $billing_phone = get_user_meta( $user_id, 'billing_phone', true ); $phone = get_user_meta( $user_id, 'phone', true ); // Prioritize billing phone number, fallback to general phone if empty $phone_number = !empty( $billing_phone ) ? $billing_phone : $phone; // Display name with ID, email, and phone number $display_name = $user->display_name . ' (#' . $user->ID . ' – ' . $user->user_email; // Append phone number if it exists if ( $phone_number ) { $display_name .= ' – ' . $phone_number; } // Close the display string $display_name .= ')'; // 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_phone_with_display' );

Leave a Reply