0

I added a custom field on Woocomerce checkout, but the ajax call to proceed checkout (?wc-ajax=checkout) does not includes the custom field 'nif'

Here's my code:


function nif_checkout_fields($checkout) {


    woocommerce_form_field( 'user_nif', array(
        'type'          => 'text',
        'class'         => array('developer_name-class form-row form-row-first'),
        'label'         => __('nif'),
        'placeholder'   => __('NIF'),
        'required'      => true,
    ), $checkout->get_value( 'user_nif' ));

}

/**
 * Process the checkout
 */
add_action('woocommerce_checkout_process', 'nif_checkout_field_process');

function nif_checkout_field_process() {
    // Check if set, if its not set add an error.
    if (empty($_POST['user_nif']) )
        wc_add_notice( __( 'Please fill in your NIF.' . $_POST['user_nif'] ), 'error' );
}

// Update the order meta with field value
add_action( 'woocommerce_checkout_update_order_meta', 'nif_checkout_field_update_order_meta', 10, 1 );
function nif_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['user_nif'] ) ) {
        update_post_meta( $order_id, 'NIF', sanitize_text_field( $_POST['user_nif'] ) );
    }
}

add_action( 'woocommerce_order_details_after_customer_details', 'display_nif_in_order_details', 10, 1 );
function display_nif_in_order_details( $order ) {

    $nif = get_post_meta( $order->get_id(), 'user_nif',  true );

    if ( ! empty( $nif ) ):
    ?>
        <table class="woocommerce-table woocommerce-table--customer-details shop_table customer_details">
            <tbody><tr>
                <th>NIF:</th>
                <td><?php echo $nif; ?></td>
            </tr></tbody>
        </table>
    <?php
    endif;
}

This is the ajax payload without NIF field

What am I doing wrong?

  • Are you call the nif_chechout_fields method in checkout page? – Mohammad Yousefi Dec 16 '21 at 12:57
  • **1)** `function nif_checkout_fields($checkout) {` is not called. **2)** You're using `update_post_meta( $order_id, 'NIF..`, however with get_meta you use `user_nif`.. in short, your code contains errors and shortcomings, go through this step by step and the issue will come up automatically – 7uc1f3r Dec 16 '21 at 13:09

0 Answers0