I'm trying to validate the Company Name field for a unique value for each user in the WooCommerce registration form, but I'm having trouble:
// That's what I got, but it doesn't work...
add_action( 'woocommerce_created_customer', 'custom_billing_company_validation');
function custom__billing_company_validation( $data, $errors ) {
$billing_company = isset( $data['billing_company'] ) ? sanitize_text_field( $data['billing_company'] ) : '';
if ( ! empty( $billing_company ) ) {
global $wpdb;
$count =$wpdb->get_row("SELECT 1 FROM $wpdb->usermeta WHERE
$wpdb->usermeta.meta_key = 'billing_company' AND $wpdb->usermeta.meta_value = '$billing_company' AND $wpdb->usermeta.user_id != $user->ID");
if ( $count > 0 ) {
$errors->add( 'validation', __('The "Name Company " already exists, please contact us.') );
}
}
}
Update 2: Here below I use a generic function that checks I some user metadata exist. Add this function yo your existing code:
Then from Show or hide WooCommerce registration fields based on a selected field value answer code, replace
account_registration_field_validation()function with the following:Code goes in functions.php file of your child theme (or in a plugin). Tested and works.