Format billing phone number on WooCommerce checkout

南楼画角 提交于 2021-02-18 18:12:01

问题


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)


回答1:


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.




回答2:


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



回答3:


Another approach that worked for me is given here.

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


来源:https://stackoverflow.com/questions/54700465/format-billing-phone-number-on-woocommerce-checkout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!