2

在 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 Number 字段(自定义结帐字段)中输入任何值,然后通过单击“下订单”按钮进入付款屏幕并返回结帐页面而不完成交易,所有默认的 woocommerce 字段(如帐单电话、电子邮件等)都会自动填充会议。

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

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

4

1 回答 1

1

更新 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 文件中。它应该工作。

注意:对于信息,该WC_Checkout方法get_value()使用用户元数据。

于 2021-02-28T15:11:27.817 回答