1
votes

Using Wordpress/Woocommerce.

I have this code which adds a custom billing field in checkout page called: "NIF/CIF". It works fine but its value it not saved in the customer account "Billing Address" data.

Once the customer makes a first order all billing address values are saved in his account: Address, State, Country, etc. But my custom field is not saved.

I guess that in my function is missing a line of code to save its value in the database, but I don't know how to start with this.

/*******************************
    CUSTOM BILLING FIELD
*********************************/
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');

function custom_woocommerce_billing_fields($fields)
{

    $fields['nif_cif'] = array(
        'label' => __('NIF/CIF', 'woocommerce'), // Add custom field label
        'placeholder' => _x('NIF/CIF', 'placeholder', 'woocommerce'), // Add custom field placeholder
        'required' => true, // if field is required or not
        'clear' => false, // add clear or not
        'type' => 'text', // add field type
        'class' => array('my-css')    // add class name
    );

    return $fields;
}
2

2 Answers

1
votes

Here is an example of how to save your custom field:

add_action( 'woocommerce_checkout_order_processed', 'prefix_save_field_on_checkout', 11, 2 );
function checkout_order_processed_add_referral_answer( $order_id, $posted ) {
    if ( ! isset( $_POST['nif_cif'] ) ) {
        return;
    }

    $order = wc_get_order( $order_id );

    // WC < 3.0
    update_post_meta( $order->id, 'order_meta_field_name', wc_clean( $_POST['nif_cif'] ) );

    // WC > 3.0
    $order->add_meta_data( 'order_meta_field_name', wc_clean( $_POST['nif_cif'] ), true );
    $order->save();
}
0
votes

Adding an extra field through 'woocommerce_billing_fields' hook is not enough. you are missing out two things.

  1. Proper validation of NIF/CIF field using 'woocommerce_after_checkout_validation' hook
  2. Saving data in order using 'woocommerce_checkout_order_processed' hook