使用 WooCommerce 中的 WC_Checkout get_value() 方法获取结帐自定义字段提交的值

Get checkout custom field submitted value using WC_Checkout get_value() method in WooCommerce

在 WooCommerce 结帐页面中,我使用以下代码添加了一个自定义字段:

add_action( 'woocommerce_before_order_notes', 'bbloomer_add_custom_checkout_field' );
function bbloomer_add_custom_checkout_field( $checkout ) { 
    $current_user = wp_get_current_user();
    $saved_gst_no = $current_user->gst_no;

    woocommerce_form_field( 'gst_no', array(        
        'type'        => 'text',        
        'class'       => array( 'form-row-wide' ),        
        'label'       => 'GST Number',        
        'placeholder' => 'GST Number',        
        'required'    => true
        //'default'   => $saved_gst_no,        
    ), $checkout->get_value( 'gst_no' ) );

    error_log( $checkout->get_value( 'gst_no' ) );
}

在 GST 编号字段 (自定义结帐字段) 中输入任何值,然后通过单击“下订单”按钮进入付款屏幕并返回结帐页面而不完成交易,所有默认的 woocommerce 字段,如账单 phone、电子邮件等都是从会话中自动填充的。

但是,通过上述代码添加的自定义字段始终为空。我尝试记录 $checkout->get_value( 'gst_no' ) 的值,但它始终为空。

如何使 $checkout 对象存储自定义字段值?

更新 2

因为您也需要将 'gst_no' 自定义字段值保存为用户数据。以下将将该自定义字段保存为用户元数据:

add_action( 'woocommerce_checkout_update_customer', 'action_checkout_update_customer', 10, 2 );
function action_checkout_update_customer( $customer, $data  ) {
    if( isset($_POST['gst_no']) ) {
        $customer->update_meta_data( 'gst_no', sanitize_text_field($_POST['gst_no']) );
    }
}

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该有效。

Note: For info, the WC_Checkout method get_value() use the user meta data.