Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.