Skip to content
Advertisement

Add checkout custom fields data to shipping packages for calculations in WooCommerce

I’m creating a plugin that will calculate custom shipping variants with API. I have a jQuery script that calculates postal and fias codes based on an entered address.

JavaScript

To store the fias code, I created custom field.

JavaScript

The calculate_shipping() method in WC_Shipping_Method in woocommerce calculates shipping options using the $ package variable, which has an ‘destination’ array field with information about the shipping address. The postal code is passed into this array by default. But I also need to pass my custom field inside $package.

As I understand it, the field that I created will save the information added there via the jQuery script, only after the form is posted. But other fields included in $package[‘destination’] are saved immediately after adding information to them.

How do I add data from a custom field in the checkout form to the $package['destination'] variable?

Advertisement

Answer

I can’t test (or modify) your jQuery code, so you will have to handle it yourself, maybe making some changes to it. I have revisited completely all your code (except your jQuery code) and everything works as you expect.

So $package['destination'] will have an additional entry for 'fias_code'.

The commented code:

JavaScript

This code goes in functions.php file of the active child theme (or active theme). Tested and works.


Important notes:

Displaying and save fias_code checkout fields:
I am using woocommerce_billing_fields and woocommerce_shipping_fields filter hooks instead of woocommerce_checkout_fields as that way the data is saved itself as order meta data and user meta data. So your last function is not required anymore.
The order meta keys start with an underscore like all billing and shipping order metadata.
The fields will be displayed on My account edit addresses… So if you want to avoid that you will need to add a condition to both related hooks.

Regarding my jQuery code:
You should better copy it to an external file and register/enqueue it in a clean WordPress way, restricting output to checkout page only. Then you will remove the related action hook and the hooked function…

Regarding action and filter hooks:
You will have to change all add_action() and add_filter() for your plugin like:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement