How to add a country calling code prefix in Woocommerce billing phone field?

Adding phone prefixes to your checkout page could be beneficial if you run a Woocommerce store and cater to international customers. This feature allows customers from various countries to easily input their phone numbers, making the purchasing process smoother. In this blog post, I’ll walk you through the steps to include a country-calling code prefix in the billing phone field of Woocommerce.

Step 1: Install and Activate the Code Snippets plugin

So, if you want to add a country-calling code prefix in the Woocommerce billing phone field, use this snippet below. If you don’t know where to add the code snippet, then add it either to your child theme’s functions.php file or better yet, use a snippet manager like Code Snippets

There is also a WpCodeBox plugin, my favorite code snippets manager for WordPress. This is a premium plugin and if you’re interested, then grab WPCodeBox with a nice 20% discount here (SAVE 20% Coupon WPSH20).
Take a closer look »

Step 2: Paste the snippet here below

After installing and activating the plugin, you must add a new snippet. So, go to Snippets >> Add new and give it a title. For example: “Add country calling code prefix in Woocommerce billing phone”. Next, paste the snippet here below inside the code box and choose “Run snippet everywhere”. Now choose “Save and activate”

// Add country calling code prefix in woocommerce billing phone
// Register WordPress hooks and callbacks for the WooCommerce checkout.
add_action( 'wp_footer', 'wpsh_add_callback_script' );
add_action( 'wp_ajax_nopriv_append_country_prefix_in_billing_phone', 'wpsh_add_phone_prefix' );
add_action( 'wp_ajax_append_country_prefix_in_billing_phone', 'wpsh_add_phone_prefix' );
add_action( 'woocommerce_checkout_process', 'wpsh_validate_phone' );

/* Outputs the JavaScript required for updating the billing phone with the country prefix. */
function wpsh_add_callback_script() {
    // Securely pass data to JavaScript.
    $ajax_url = admin_url('admin-ajax.php');
    ?>
    <script type="text/javascript">
        (function($) {
            $(document.body).on('updated_checkout', function() {
                var country_code = $('#billing_country').val();
                var ajax_data = {
                    action: 'append_country_prefix_in_billing_phone',
                    country_code: country_code
                };

                $.post('<?php echo esc_js($ajax_url); ?>', ajax_data, function(response) {
                    $('#billing_phone').val(response);
                });
            });
        })(jQuery);
    </script>
    <?php
}

/* Handles AJAX request to append the country calling code to the billing phone field. */
function wpsh_add_phone_prefix() {
    $country_code = isset($_POST['country_code']) ? sanitize_text_field($_POST['country_code']) : '';
    $calling_code = '';

    if ($country_code) {
        $calling_codes = WC()->countries->get_country_calling_code($country_code);
        $calling_code = is_array($calling_codes) ? $calling_codes[0] : $calling_codes;
    }

    echo $calling_code;
    wp_die(); 
}

/* Validates the phone number length during the WooCommerce checkout process. */
function wpsh_validate_phone() {
    if (isset($_POST['billing_phone']) && strlen(preg_replace('/[^0-9]/', '', $_POST['billing_phone'])) < 6) {
        wc_add_notice(__('Billing Phone must be at least 6 digits long.', 'woocommerce'), 'error');
    }
}

Pay attention that lines 37-46 are added because with this snippet phone number field is filled with the prefix and appears as completed in the Woocommerce checkout. This way the user can proceed with the order even without entering the rest of the number. To avoid this we add another small piece of code that won’t allow to enter phone numbers with less than 6 digits. You can modify this in line 42 and the message itself in line 43.

Step 3: Test the Checkout Page

After setting up the plugin, it’s essential to test the checkout page to confirm that the phone prefix functions properly. To do this, simply add an item to your cart and head to the checkout page. You should notice a prefix appearing next to the phone number field, which updates whenever you select a different country. Ensure that the phone number is validated accurately and that the country code is included when the order is placed.

Alternative method: Install the “Country code selector” plugin

If the earlier method feels a bit overwhelming, you might consider installing and activating the “Country code selector” plugin. This handy tool enables you to incorporate phone prefixes directly on the Woocommerce checkout page. You can easily locate this plugin in the WordPress plugin directory and install it from there.

To sum up, including phone prefixes on the Woocommerce checkout page is quite advantageous for international customers. It simplifies the process of entering their phone numbers and minimizes the chances of errors during checkout.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart
Scroll to Top