Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Make last name field unique for guests on WooCommerce checkout

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;
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 );
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!