Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda