Best Way to Limit Zip Code to 5 Characters Only When Country is USA in Woo Checkout

[ad_1]

The title pretty much says it all. I've successfully limited it to 5 for all checkouts, but only with the country being the US seems more challenging. My assumption is I will have to insert some Javascript via functions.php. Do you have any other ideas?

[ad_2]
1 Comment
  1. yes I insert the following into functions.php file in a CHIKD THEME PLEASE, OR YOU WILL LOSE IT ON UODATE AMD NOT EVEN REMEBRR ABOUT IT

    add_action(‘woocommerce_after_checkout_validation’, ‘custom_validate_us_zipcode’, 10, 2);

    function custom_validate_us_zipcode($fields, $errors) {
    // Check if the billing country is set to the US
    if (isset($fields[‘billing_country’]) && $fields[‘billing_country’] === ‘US’) {
    $zipcode = $fields[‘billing_postcode’];

    // Check if the zip code is 5 characters long
    if (strlen($zipcode) !== 5 || !ctype_digit($zipcode)) {
    $errors->add(‘validation’, __(‘Please enter a valid 5-digit US zip code.’, ‘woocommerce’));
    }
    }
    }

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer