Tidy Names and Postcodes Entered at Checkout
Cleans up what customers type before the order is saved: names get proper capitals, postcodes become upper case and stray spaces are removed.
Opens WPIDE on
Code
add_filter( 'woocommerce_checkout_posted_data', function ( $data ) {
foreach ( array( 'billing', 'shipping' ) as $type ) {
foreach ( array( 'first_name', 'last_name', 'city', 'address_1', 'address_2', 'company' ) as $field ) {
$key = $type . '_' . $field;
if ( empty( $data[ $key ] ) || ! is_string( $data[ $key ] ) ) {
continue;
}
$value = trim( preg_replace( '/\s+/u', ' ', $data[ $key ] ) );
if ( in_array( $field, array( 'first_name', 'last_name', 'city' ), true ) && ( mb_strtolower( $value ) === $value || mb_strtoupper( $value ) === $value ) ) {
$value = mb_convert_case( mb_strtolower( $value ), MB_CASE_TITLE, 'UTF-8' );
}
$data[ $key ] = $value;
}
if ( ! empty( $data[ $type . '_postcode' ] ) && is_string( $data[ $type . '_postcode' ] ) ) {
$data[ $type . '_postcode' ] = strtoupper( trim( preg_replace( '/\s+/', ' ', $data[ $type . '_postcode' ] ) ) );
}
}
if ( ! empty( $data['billing_email'] ) && is_string( $data['billing_email'] ) ) {
$data['billing_email'] = strtolower( trim( $data['billing_email'] ) );
}
return $data;
} );
Notes
Names typed in mixed case, such as "McDonald", are left as typed; only all-lower or all-upper names are changed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.