Search code examples
phpwordpresswoocommerceformatcheckout

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)


Solution

  • 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.