Make Last Name Field Unique For Guests On WooCommerce Checkout

- 1 answer

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

  • Use woocommerce_after_checkout_validation action hook for validation
  • Your code is vulnerable to SQL injection, use prepared statements
  • $wpdb: prefix is giving the table prefix of the site. So generating table name dynamically through this will help to keep the query correct even on many sites with different table prefixes
  • Your code will be executed for both guests and logged in users

So 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 );