Search code examples
javascriptphpcsswoocommercehook-woocommerce

WooCommerce: Capitalize input to the billing address field at checkout + update the order meta?


I've been asked to add formatting code to the checkout fields to force a change to the title case when a customer either has caps lock on or is typing in all lowercase, as these values need to be passed through to the client's Quickbooks account with proper capitalization. As of now, everything works except for the address field, likely because numbers precede most entries. Case change works when input on the checkout page in all lowercase, but once an order is placed it appears the way I typed it. Here is what I have so far:

function wc_checkout_alter_field_input() {
    if (is_checkout()):
        if (!wp_script_is('jquery', 'done')) {
            wp_enqueue_script('jquery');
        }

        wp_add_inline_script('wc-checkout', 'jQuery(document).ready(function($){ $("#billing_address_1").keyup(function() { $(this).val($(this).val().substr(0, 1).toUpperCase() + $(this).val().substr(1).toLowerCase());});});');
    

add_action('wp_enqueue_scripts', 'wc_checkout_alter_field_input');
#billing_address_1 {
    text-transform: capitalize;
}

I have tried using the code I specified for all of the checkout fields. It is only this one I have issues with, as both numbers and letters need to be entered as an address. I am trying to force submitted orders to have addresses display as title case (123 Example St).

I'm guessing I need to add Regex somewhere, but I'm not familiar with it and would appreciate any insight as to how I could go about using it, if necessary.


Solution

  • If you are concerned with how the values are being saved in the database, you would need to add custom code to your website that hooks into the action that saves the checkout fields, which is woocommerce_checkout_posted_data found here.

    add_filter('woocommerce_checkout_posted_data', 'my_custom_woocommerce_checkout_posted_data');
    function my_custom_woocommerce_checkout_posted_data($data){
      // The data posted by the user comes from the $data param. 
      // You would look for the fields being posted, 
      // like "billing_first_name" and "billing_last_name"
    
      if($data['billing_first_name']){
        /*
          From hello world to Hello World
        */
        $data['billing_first_name'] = ucwords($data['billing_first_name']);
      }
    
      if($data['billing_last_name']){
        $data['billing_last_name'] = ucwords($data['billing_last_name']);
      }
    
      return $data;
    }