j92
j92

Reputation: 45

Format billing phone number on WooCommerce checkout

For the WooCommerce checkout billing field, how can I make this field require 9 numbers and insert dashes for proper phone formatting? For example, instead of typing out 3053453212 in the phone number field, it displays: (305-345-3212)

Upvotes: 2

Views: 8105

Answers (3)

burf
burf

Reputation: 370

Another approach that worked for me is given here.

$_POST['billing_phone'] = preg_replace("/^(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $number);

Upvotes: 0

user8020913
user8020913

Reputation:

You can try this

/** 
*  Require 9 digit number. Format to 000-000-0000 at submission
*  stackoverflow/54700465
*/

add_filter( 'woocommerce_billing_fields', 'wc_filter_phone', 10, 1 );
function wc_filter_phone( $address_fields ) {
    $address_fields['billing_phone']['min-lenght="9"'];
    $format_number = preg_replace("/^(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $address_fields);
    return $format_number;  
}

// End

Upvotes: 3

LoicTheAztec
LoicTheAztec

Reputation: 253784

Based on "Formatting a phone number in a form using jquery" answer code, here is the way to format the Woocommerce billing phone:

add_action('wp_footer', 'format_checkout_billing_phone');
function format_checkout_billing_phone() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('#billing_phone').on( 'input focusout', function() {
            var p = $(this).val();

            p = p.replace(/[^0-9]/g, '');
            p = p.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
            $(this).val(p);
        });
    });
    </script>
    <?php
    endif;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 7

Related Questions