Limit Address Line Length for Shipping Labels
Stops checkout when an address line is longer than your carrier's label allows (often 35 characters) and asks the customer to use the second line.
Opens WPIDE on
Code
$wpide_address_max = 35; // Maximum characters per address line.
add_filter( 'woocommerce_default_address_fields', function ( $fields ) use ( $wpide_address_max ) {
foreach ( array( 'address_1', 'address_2', 'company' ) as $key ) {
if ( isset( $fields[ $key ] ) ) {
$fields[ $key ]['maxlength'] = $wpide_address_max;
}
}
return $fields;
} );
add_action( 'woocommerce_after_checkout_validation', function ( $data, $errors ) use ( $wpide_address_max ) {
foreach ( array( 'billing_address_1', 'billing_address_2', 'shipping_address_1', 'shipping_address_2' ) as $key ) {
if ( ! empty( $data[ $key ] ) && mb_strlen( (string) $data[ $key ] ) > $wpide_address_max ) {
$errors->add( 'validation', sprintf( 'Address lines can be up to %d characters. Please move the rest to the second address line.', $wpide_address_max ) );
return;
}
}
}, 10, 2 );
Notes
Also sets a maxlength on the fields so customers see the limit while typing.
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.