簡體   English   中英

使用 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 字段,如計費電話、email 等都是自動填充的session。

但是,通過上述代碼添加的自定義字段始終為空白。 我嘗試記錄$checkout->get_value( 'gst_no' )的值,它始終是 null。

如何使$checkout object 存儲自定義字段值?

更新 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()使用用戶元數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM