如何使用之前输入的值填充自定义结帐字段,例如默认的 WooCommerce 结帐字段?

2024-02-12

我使用以下代码添加了一个自定义字段:

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' ) ); 
}

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

但是,通过上述代码添加的自定义字段始终为空。如何在访客用户的自定义字段中自动填充之前输入的值,类似于自动填充默认 woocommerce 字段的方式?


Updated (替换错了WC_Session method set() with get()在第一个函数上)

这适用于访客用户。将您的代码替换为:

// Display checkout custom field
add_action( 'woocommerce_before_order_notes', 'add_custom_checkout_field' );
function add_custom_checkout_field( $checkout ) { 
    $key_field = 'gst_no';
       
    woocommerce_form_field( $key_field, array(        
        'type'        => 'text',        
        'class'       => array( 'form-row-wide' ),        
        'label'       => __('GST Number'),        
        'placeholder' => __('GST Number'),        
        'required'    => true
        //'default'   => $saved_gst_no,        
    ), $checkout->get_value($key_field) ? $checkout->get_value($key_field) : WC()->session->get($key_field) ); 
}

// Save checkout custom field value in a WC_Session variable 
add_action( 'woocommerce_checkout_create_order', 'action_checkout_create_order', 10, 2 );
function action_checkout_create_order( $order, $data  ) {
    $key_field = 'gst_no';
    
    if( isset($_POST[$key_field]) ) {
        WC()->session->set($key_field, sanitize_text_field($_POST[$key_field]));
    }
}

// Save checkout custom field value as user meta data
add_action( 'woocommerce_checkout_update_customer', 'action_checkout_update_customer', 10, 2 );
function action_checkout_update_customer( $customer, $data  ) {
    $key_field = $key_field;
    
    if( isset($_POST['gst_no']) ) {
        $customer->update_meta_data($key_field, sanitize_text_field($_POST[$key_field]));
    }
}

Note:使用 WC_Session 变量存储客人提交的值,允许在未完成交易而返回时在结账时显示该值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用之前输入的值填充自定义结帐字段,例如默认的 WooCommerce 结帐字段? 的相关文章

随机推荐