获取并显示WooCommerce中自定义结帐字段中输入的数据。

huangapple go评论73阅读模式
英文:

Get and display the inputed data from custom Checkout fields in WooCommerce

问题

You've already added a checkbox to show/hide custom fields in your WooCommerce Checkout page using the provided code. However, you're having trouble getting input data from your customers. You've also tried a code snippet to save the submitted input data when placing an order, but it's not working.

Please let me know what specific assistance you need with this code or if you have any questions related to it.

英文:

I already add checkbox to show/hide custom field in my WooCommerce Checkout page at functions.php and the code is working well but I can't get input data from my customer. Where/How can I get it? I've tried so many codes and losing so much my time.

Here is the code that displays my custom checkout fieds:

add_filter( 'woocommerce_checkout_fields' , 'rws_display_checkbox_and_new_checkout_field' ); 
function rws_display_checkbox_and_new_checkout_field( $fields ) {

    $fields['billing']['have_vat_number'] = array(
        'type'      => 'checkbox',
        'label'     => __('ต้องการใบกำกับภาษี', 'woocommerce'),
        'class'     => array('form-row-wide'),
        'clear'     => true
    );   
    $fields['billing']['vat_name'] = array(
        'label'     => __('ชื่อ – สกุล / บริษัท', 'woocommerce'),
        'placeholder'   => _x(' ', 'placeholder', 'woocommerce'),
        'class'     => array('form-row-wide'),
        'clear'     => true
    );
    $fields['billing']['vat_number'] = array(
        'label'     => __('หมายเลขผู้เสียภาษี', 'woocommerce'),
        'placeholder'   => _x(' ', 'placeholder', 'woocommerce'),
        'class'     => array('form-row-wide'),
        'clear'     => true
    );
    $fields['billing']['vat_address'] = array(
    	'type'      => 'textarea',
        'label'     => __('ที่อยู่', 'woocommerce'),
        'placeholder'   => _x(' ', 'placeholder', 'woocommerce'),
        'class'     => array('form-row-wide'),
        'clear'     => true
    );
    return $fields;

}

This code show / hide some custom fields on a checkbox click:

add_action( 'woocommerce_after_checkout_form', 'rws_conditionally_hide_show_new_field', 9999 );
function rws_conditionally_hide_show_new_field() {
  wc_enqueue_js( "
      jQuery('input#have_vat_number').change(function(){
         if (! this.checked) {
            jQuery('#vat_name_field').fadeOut();
            jQuery('#vat_name_field input').val('');
			jQuery('#vat_number_field').fadeOut();
            jQuery('#vat_number_field input').val(''); 
			jQuery('#vat_address_field').fadeOut();
            jQuery('#vat_address_field input').val(''); 
         } else {
            jQuery('#vat_name_field').fadeIn();
			jQuery('#vat_number_field').fadeIn();
			jQuery('#vat_address_field').fadeIn();
         } 
      }).change();
  ");  
	if ( isset( $_POST['billing']['have_vat_number'] ) ) {
        $have_vat_number = $_POST['billing']['have_vat_number'];
    }

    if ( isset( $_POST['billing']['vat_name'] ) ) {
        $vat_name = $_POST['billing']['vat_name'];
    }

    if ( isset( $_POST['billing']['vat_number'] ) ) {
        $vat_number = $_POST['billing']['vat_number'];
    }

    if ( isset( $_POST['billing']['vat_address'] ) ) {
        $vat_address = $_POST['billing']['vat_address'];
    }
}

Then I've tried this code to save submitted input data when placing an order, but is still not working:

add_action('woocommerce_checkout_update_order_meta', 'rws_save_custom_checkout_field_data');

function rws_save_custom_checkout_field_data($order_id) {
    if ($_POST['billing']['have_vat_number']) {
        $have_vat_number = sanitize_text_field($_POST['billing']['have_vat_number']);
        update_post_meta($order_id, 'Have VAT Number', $have_vat_number);
    }

    if ($_POST['billing']['vat_name']) {
        $vat_name = sanitize_text_field($_POST['billing']['vat_name']);
        update_post_meta($order_id, 'VAT Name', $vat_name);
    }

    if ($_POST['billing']['vat_number']) {
        $vat_number = sanitize_text_field($_POST['billing']['vat_number']);
        update_post_meta($order_id, 'VAT Number', $vat_number);
    }

    if ($_POST['billing']['vat_address']) {
        $vat_address = sanitize_textarea_field($_POST['billing']['vat_address']);
        update_post_meta($order_id, 'VAT Address', $vat_address);
    }
}

Any help is appreciated.

答案1

得分: 0

你可以始终使用一个技巧 - var_dump($_POST);exit; 或 error_log(print_r($_POST,true));
通过这种方式,你将了解在表单提交时它是如何发送的。

尝试使用$_POST['vat_name']而不是$_POST['billing']['vat_name']。

英文:

You can always use a trick - var_dump($_POST);exit; or error_log(print_r($_POST,true));
With this you will get to know how it's send on form submission.

Try $_POST['vat_name'] instead of $_POST['billing']['vat_name']

答案2

得分: 0

以下是您的代码的翻译部分:

您的代码中存在一些错误,一些缺少的部分,以及您没有使用正确的挂钩。

在以下经过重新审查的代码中(并进行了评论),我已经做了以下更改:

- 添加了一个使用您的字段设置(字段键、类型和标签)的自定义函数,以使代码更紧凑和高效。
- 添加了结帐字段验证。
- 将您的jQuery代码压缩为高效的方式(并使其在“我的帐户编辑账单地址”部分也能正常工作)。
- 更改了结帐字段挂钩,以允许在客户的“我的帐户编辑账单地址”部分显示字段,允许客户编辑或删除其增值税数据。
- 添加了一个挂钩函数,以将数据保存为用户元数据,这允许:
    - 在客户已经提交了带有填写的增值税字段的订单时,在结帐增值税字段中显示字段值。
    - 在客户已经提交了带有填写的增值税字段的订单时,在我的帐户编辑账单地址字段中显示字段值。
- 添加了一个挂钩函数,以在管理员订单页面显示增值税字段的值。

以下是完整的代码:

请注意,这是您代码的翻译部分,包括对代码中所做更改的描述。如果您需要进一步的帮助或解释,请告诉我。

英文:

There are some mistakes in your code, some missing things, and you are not using the correct hooks.

In the following revisited code (and commented), I have:

  • added a custom function with your field settings (field keys, type and label) that will allow making the code more compact and efficient.
  • added the checkout field validation
  • compacted your jQuery code in an efficient way (and make it work also in My account Edit Billing address section).
  • changed the checkout field hook to allow it displaying also the fields in the customer My account Edit Billing Address section, allowing the customer to edit or remove his VAT data.
  • added a hooked function to save the data as user metadata, that allows to:
    • display the field values in checkout VAT fields when customer has already submitted an order with filled in VAT fields.
    • display the field values in My account Edit Billing address fields when customer has already submitted an order with filled in VAT fields.
  • added a hooked function to display VAT fields values in Admin Order pages

Here is the complete code:

// Taxpayer Field settings
function taxpayer_fields_settings() {
$domain = 'woocommerce';
// Here we set all required data in the array to display checkout fields
return array(
'billing_has_vat_number' => array(
'type'  =>   'checkbox',
'label' => __('ต้องการใบกำกับภาษี', $domain), // Need a tax invoice
),
'billing_vat_name' => array(
'type'  =>   'text',
'label' => __('ชื่อ – สกุล / บริษัท', $domain),  // Taxpayer Name & Company
),
'billing_vat_number' => array(
'type'  =>   'text',
'label' => __('หมายเลขผู้เสียภาษี', $domain), // Taxpayer number
),
'billing_vat_address' => array(
'type'  =>   'textarea',
'label' =>  __('ที่อยู่', $domain),  // Taxpayer address
)
);
}
// Display Taxpayer Fields in checkout and My account Edit Billing Address
add_filter( 'woocommerce_billing_fields' , 'add_checkout_taxpayer_custom_fields' ); 
function add_checkout_taxpayer_custom_fields( $billing_fields ) {
// Loop through fields settings data array
foreach ( taxpayer_fields_settings() as $field_key => $field_data ) {
$billing_fields[$field_key] = array(
'type'      => $field_data['type'],
'label'     => $field_data['label'],
'placeholder'   => _x(' ', 'placeholder', 'woocommerce'),
'class'     => array('form-row-wide'),
'clear'     => true
); 
}
return $billing_fields;
}
// jQuery: Show / Hide Taxpayer Fields in checkout and My account Edit Billing Address
add_action( 'wp_head', 'checkout_taxpayer_custom_fields_js' );
function checkout_taxpayer_custom_fields_js() {
// Only on checkout page and My Account Edit Address
if( ( is_checkout() && ! is_wc_endpoint_url() ) || is_wc_endpoint_url( 'edit-address' ) ) :
wc_enqueue_js( "jQuery(function($){
$('input#billing_has_vat_number').change(function(){
if (! this.checked) {
$('#billing_vat_name_field,#billing_vat_number_field,#billing_vat_address_field').fadeOut();
$('#billing_vat_name_field input,#billing_vat_number_field input,#billing_vat_address_field textarea').val(''); 
} else {
$('#billing_vat_name_field,#billing_vat_number_field,#billing_vat_address_field').fadeIn();
} 
}).change();
});");
endif;
}
//  Taxpayer checkout fields Validation
add_action('woocommerce_checkout_process', 'checkout_taxpayer_custom_fields_validation');
function checkout_taxpayer_custom_fields_validation() {
$fields_data = taxpayer_fields_settings(); // Load checkout fields settings data array
$has_vat_key = array_key_first( $fields_data ); // Get the first field key
if ( isset($_POST[$has_vat_key]) && $_POST[$has_vat_key] ) {
array_shift($fields_data);
foreach( $fields_data as $field_key => $field_data ) {
if ( isset($_POST[$field_key]) && ! $_POST[$field_key] ) {
wc_add_notice( sprintf( __( 'Please fill in "%s" field' ), $field_data['label'], 'woocommerce' ), 'error' );
}
}
}
}
// Save Order Taxpayer checkout fields values
add_action( 'woocommerce_checkout_create_order', 'save_order_meta_taxpayer_custom_fields' );
function save_order_meta_taxpayer_custom_fields( $order ) {
$fields_data = taxpayer_fields_settings(); // Load checkout fields settings data array
$has_vat_key = array_key_first( $fields_data ); // Get the first field key
if ( isset($_POST[$has_vat_key]) && $_POST[$has_vat_key] ) {
$order->update_meta_data( '_' . $has_vat_key, 'yes' ); // update order meta
array_shift($fields_data);
foreach( $fields_data as $field_key => $field_data ) {
if ( isset($_POST[$field_key]) && $_POST[$field_key] ) {
if( $field_data['type'] === 'text' ) {
$order->update_meta_data( '_' . $field_key, sanitize_text_field($_POST[$field_key]) ); // update order meta
} else {
$order->update_meta_data( '_' . $field_key, sanitize_textarea_field($_POST[$field_key]) ); // update order meta
}
}
}
}
}
// Save Customer Taxpayer checkout fields values
add_action( 'woocommerce_checkout_update_customer', 'save_customer_meta_taxpayer_custom_fields' );
function save_customer_meta_taxpayer_custom_fields( $customer ) {
$fields_data = taxpayer_fields_settings(); // Load checkout fields settings data array
$has_vat_key = array_key_first( $fields_data ); // Get the first field key
if ( isset($_POST[$has_vat_key]) && $_POST[$has_vat_key] ) {
$customer->update_meta_data( $has_vat_key, 1 ); // update customer meta
array_shift($fields_data);
foreach( $fields_data as $field_key => $field_data ) {
if ( isset($_POST[$field_key]) && $_POST[$field_key] ) {
if( $field_data['type'] === 'text' ) {
$customer->update_meta_data( $field_key, sanitize_text_field($_POST[$field_key]) ); // update customer meta
} else {
$customer->update_meta_data( $field_key, sanitize_textarea_field($_POST[$field_key]) ); // update customer meta
}
}
}
}
}
// Display customer Taxpayer data in Admin Orders after Billing details
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_admin_order_taxpayer_custom_fields' );
function display_admin_order_taxpayer_custom_fields( $order ){
$fields_data = taxpayer_fields_settings(); // Load checkout fields settings data array
$has_vat_key = array_key_first( $fields_data ); // Get the first field key
$customer_has_vat = $order->get_meta( '_' . $has_vat_key ); // Get customer taxpayer if exist
if ( $customer_has_vat ) {
echo '<p><strong>' . __( 'ลูกค้าเป็นผู้เสียภาษี:', 'woocommerce' ) . '</strong>'; // Label: The customer is a taxpayer
array_shift($fields_data);
foreach( $fields_data as $field_key => $field_data ) {
$field_value = $order->get_meta( '_' . $field_key ); // Get other field data values
if( $field_value ) {
echo '<br><strong>' . $field_data['label'] . ':</strong> ' . $field_value;
}
}
echo '</p>';
}
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

In checkout page:

获取并显示WooCommerce中自定义结帐字段中输入的数据。

In My Account Edit Billing Address:

获取并显示WooCommerce中自定义结帐字段中输入的数据。

On Admin orders single page:

获取并显示WooCommerce中自定义结帐字段中输入的数据。

huangapple
  • 本文由 发表于 2023年6月13日 14:47:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76462286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定