I would like to make the entered values in last name field in checkout page unique or validate for duplicates.
This is for guests users only where they fill the first name and last name. I currently have this snippet but this does not have the desired result. Any advice?
add_action( 'woocommerce_before_checkout_billing_form', 'lastname_field' );
function validate_lastname_field($exist_error ) {
global $wpdb;
$billing_last_name = $_POST['billing_last_name'];
$results = $wpdb->get_results('SELECT * FROM `abc_usermeta` where meta_key = "billing_last_name" AND meta_value = "'.$billing_last_name.'"');
if ( $results ) {
$exist_error->add( 'billing_last_name_error', __( 'Last name already exists.', 'woocommerce' ) );
}
return $exist_error;
}
Your code contains some mistakes
woocommerce_after_checkout_validation action hook for validationSo you get:
function action_woocommerce_after_checkout_validation( $data, $error ) {
// Only for guests
if ( is_user_logged_in() ) return;
global $wpdb;
// Billing last name
$billing_last_name = $data['billing_last_name'];
// Executes a SQL query and returns the entire SQL result.
$results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}usermeta WHERE meta_key = 'billing_last_name' AND meta_value = %s", $billing_last_name ) );
// NOT empty
if ( $results ) {
$error->add( 'validation', __( 'Last name already exists.', 'woocommerce' ) );
}
}
add_action( 'woocommerce_after_checkout_validation', 'action_woocommerce_after_checkout_validation', 10, 2 );