Changing the WooCommerce checkout fields display order is much simpler and more robust with the use of a 'priority' element in the field definition.
Someone on the Advanced WooCommerce Facebook group asked about adding a field to the WooCommerce checkout page. I went straight to Rodolfo Melogli’s oracle of WooCommerce tips and found a post about adding a house number. I gave the code a try on a local installation but it didn’t work!
What changed?
In the past fields were displayed in the order that they were in the array of fields. Changing the order of fields required you to reset the array and add the fields to the array in the new order. One downside to this was that fields added by other plugins would likely not be in the updated array.
Rodolfo’s post was written in July 2016 and updated in April 2018, around the time of WooCommerce 3.3.5. WooCommerce changed how the display order was determined (I think it changed in 3.5 but it might have been earlier) – it now uses the ‘priority‘ element of the field’s array. Without this element the new field is placed below the other fields.
Adding the new element
The get_default_address_fields() function in includes/class-wc-countries.php creates the address fields. Each is given a priority 10 greater than the next field.
Updating Rodolfo’s code was simple – I added a ‘priority‘ element to the field’s array. Instead of hard coding a priority number, I added 5 to the priority of the field I wanted the new field to be displayed after.
I reported this update to Rodolfo in a comment on the original post.
The new method of ordering fields also allows for the removal of the code that reloaded the arrays (the $newfields array in Rodolfo’s code).
Advantages
The new ordering system is much easier to use. It is also more robust – if another plugin adds a field then my code doesn’t have to know about it. The new field will still be displayed.
Leave a Reply