function tzn_woocommerce_billing_fields($billing_fields) {
$fields = "";
if ($fields && is_countable($fields)) {
foreach ($fields as $key => $field) {
if (is_user_logged_in() && $key == 'billing_email_2') {
continue;
}
$billing_fields[$key] = $field;
}
}
return $billing_fields;
}
add_filter('woocommerce_billing_fields', 'tzn_woocommerce_billing_fields', 9999, 2);
/* Add */
function tzn_add_extended_fields() {
wp_enqueue_script('wc-country-select');
wp_enqueue_script('wc-address-i18n');
wp_enqueue_script('wc-checkout');
if (!isset($_GET['handler']))
echo '<p class="title_billing_title">' . __("Persönliche Informationen", "tzn") . '</p>';
$checkout = WC_Checkout::instance();
$fields = $checkout->get_checkout_fields('billing');
$skip_fields = array('billing_email', 'billing_email_2');
if (isset($_GET['handler']))
$skip_fields = array('billing_title', 'billing_email', 'billing_email_2');
foreach ($fields as $key => $field) {
if (in_array($key, $skip_fields)) {
continue;
}
if (isset($field['country_field'], $fields[$field['country_field']])) {
$field['country'] = $checkout->get_value($field['country_field']);
}
woocommerce_form_field($key, $field, $checkout->get_value($key));
}
}
add_action('woocommerce_register_form', 'tzn_add_extended_fields', 1);
/* Save */
function tzn_save_extended_fields($customer_id) {
if (!isset($_GET['handler'])) return;
if (defined('REST_REQUEST')) {
return true;
}
$checkout = WC_Checkout::instance();
$fields = $checkout->get_checkout_fields('billing');
foreach ($fields as $key => $field) {
if ($key == 'billing_email') {
continue;
}
if (!isset($_POST[$key])) {
continue;
}
update_user_meta($customer_id, $key, sanitize_text_field($_POST[$key]));
if ($key == 'billing_first_name') {
update_user_meta($customer_id, 'first_name', sanitize_text_field($_POST[$key]));
}
if ($key == 'billing_last_name') {
update_user_meta($customer_id, 'last_name', sanitize_text_field($_POST[$key]));
}
if ($key == 'unternehmen') {
update_field( 'unternehmen', sanitize_text_field($_POST[$key]),'user_' . $customer_id);
update_user_meta($customer_id, 'unternehmen', sanitize_text_field($_POST[$key]));
}
if ($key == 'ust_idnr') {
update_user_meta($customer_id, 'ust_idnr', sanitize_text_field($_POST[$key]));
update_field( 'ust_idnr', sanitize_text_field($_POST[$key]),'user_' . $customer_id);
}
}
if (isset($_POST['billing_title'])) {
update_user_meta($customer_id, 'billing_title', wc_clean($_POST['billing_title']));
}
}
add_action('woocommerce_created_customer', 'tzn_save_extended_fields');
add_action('woocommerce_save_account_details', 'tzn_save_extended_fields');
Account, Child Test
Customize register form to add fields
woocommerce_register_form
