I have followed a tutorial on how to include custom fields at checkout in woocommerce, everything works, as expected but I want to save the full billing address to this custom field if is not filled.
This is what I have
function cloudways_save_extra_checkout_fields( $order_id, $posted ){
// don't forget appropriate sanitization if you are using a different field type
if( isset( $posted['cloudways_text_field'] ) ) {
update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
if(empty($posted['cloudways_text_field']))
{
// it's empty!
update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
}
else
{
update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
}
}
} add_action( 'woocommerce_checkout_update_order_meta', 'cloudways_save_extra_checkout_fields', 10, 2 );
But I don't know how to save the array of billing address to this custom text field if it's not filled.
Link to tutorial is https://www.cloudways.com/blog/how-to-edit-delete-fields-and-email-in-woocommerce-custom-checkout-fields/amp/
Thanks in advance.
You can try building the address into an array and saving that in the field. Or you can also build it to a string, really depends what data you want the field to contain, string or array. Here is an example of an array:
function cloudways_save_extra_checkout_fields( $order_id, $posted ) {
// don't forget appropriate sanitization if you are using a different field type
if ( isset( $posted['cloudways_text_field'] ) ) {
update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
if ( empty( $posted['cloudways_text_field'] ) ) {
$billing_address_array = array(
'billing_address_1' => $posted['billing_address_1'],
'billing_address_2' => $posted['billing_address_2'],
'billing_city' => $posted['billing_city'],
'billing_postcode' => $posted['billing_postcode'],
'billing_state' => $posted['billing_state'],
'billing_country' => $posted['billing_country'],
);
update_post_meta( $order_id, '_cloudways_text_field', wc_clean( $billing_address_array ) );
} else {
update_post_meta( $order_id, '_cloudways_text_field', sanitize_text_field( $posted['cloudways_text_field'] ) );
}
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'cloudways_save_extra_checkout_fields', 10, 2 );