svelandiag
svelandiag

Reputation: 4320

Getting value from custom checkout billing field in WooCommerce

I added a field at the checkout following the woocommerce documentation this way:

/*Add document ID to checkout form*/
add_filter( 'woocommerce_checkout_fields' , 'ebani_cedula_checkout_field' );

// Our hooked in function - $fields is passed via the filter!
function ebani_cedula_checkout_field( $fields ) {
    $fields['billing']['cedula'] = array(
        'label'     => __('Cédula de ciudadanía', 'woocommerce'),
        'placeholder'   => _x('Cédula', 'placeholder', 'woocommerce'),
        'required'  => true,
        'class'     => array('form-row-last'),
        'clear'     => true,
        'priority' => 15
    );

     return $fields;
}

Then I want to show it on the admin order edit page this way:

/**
 * Display field value on the order edit page
 */
 add_action( 'woocommerce_admin_order_data_after_billing_address', 'cedula_checkout_field_display_admin_order_meta', 10, 1 );
    
 function cedula_checkout_field_display_admin_order_meta($order){
        echo '<p><strong>'.__('Cédula').':</strong> ' . get_post_meta( $order->get_id(), '_cedula', true ) . '</p>';
 }

When I go to the order edit page I get an empty value for _cedula I don't know why, I'm just following the documentation, but it is not working, how can I get the data stored in the custom checkout field?

Upvotes: 1

Views: 1593

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253849

If you want this custom billing field to be saved when order is placed, it's better to use the action hook woocommerce_billing_fields instead of woocommerce_checkout_fields like:

add_filter( 'woocommerce_billing_fields' , 'ebani_cedula_checkout_field' );
function ebani_cedula_checkout_field( $fields ) {
    $fields['billing_cedula'] = array(
        'label'       => __('Cédula de ciudadanía', 'woocommerce'),
        'placeholder' => _x('Cédula', 'placeholder', 'woocommerce'),
        'required'    => true,
        'class'       => array('form-row-last'),
        'clear'       => true,
        'priority'    => 15
    );
    return $fields;
}

add_action( 'woocommerce_admin_order_data_after_billing_address', 'cedula_checkout_field_display_admin_order_meta', 10, 1 );
function cedula_checkout_field_display_admin_order_meta($order){
    if( $value = $order->get_meta('_billing_cedula') )
        echo '<p><strong>'.__('Cédula').':</strong> ' . $value . '</p>';
}

Now your custom checkout billing field is saved.

Upvotes: 1

Related Questions