Here is a quick way to customize WooCommerce shipping and billing addresses fields order. Before providing you the code to reorder the fields, i’d like to explain how these fields are displayed. They are printed on many parts of WooCommerce: my account page, emails etc…
There are basically 4 existing functions to retrieve address fields, all located in classes/class-wc-order.php:
- get_billing_address()
- get_shipping_address()
- get_formatted_billing_address()
- get_formatted_shipping_address()
The functions that we need are get_formatted_billing_address() and get_formatted_shipping_address(). Both contain a specific filter that we can use to re-order fields:
- woocommerce_order_formatted_billing_address
- woocommerce_order_formatted_shipping_address
From these two filters, we can create custom functions that will define a custom order. To do so, we have to deal with WordPress add_filter() built-in function. The add_filter() function is a function that allows you to override specific parts of any kind of stuff within WordPress, or within any theme or plugin for WordPress. In our case the filter is applied on arrays. So, we need to create custom functions that will obviously returns arrays. Here is the snippet that will allow you to re-order billing fields. Please note that the code will apply these changes on all locations where the billing address is displayed.
From there, all you have to do is to change the order of the fields within the new array. And Boom! The magic appears. You can do the exact same thing with the shipping fields, simply adjust the filter name, and fields names. If you want to change both shipping fields and billing fields order, make sure you use two separate functions with different names. That may sound silly, but it’s not. Many people just copy and paste the same function twice in there functions.php, and of course that doesn’t work and break the website… So, just to make sure here is the code to re-order shipping fields:
And that’s it! I hope you liked it, and please feel free to discuss the code in the comments section!
Leave a Reply
You must be logged in to post a comment.