我認爲你必須覆蓋woocommerce/templates/myaccount/form-login.php
模板,並通過這樣做,你已經設法顯示billing_first_name
和billing_last_name
但您忘記使用woocommerce_created_customer
掛鉤,這需要將這些數據保存到數據庫中。
我會建議爲你保持模板,因爲它是通過function.php
添加這些字段下面是代碼以WooCommerce登記表添加自定義字段:
/**
* To add WooCommerce registration form custom fields.
*/
function text_domain_woo_reg_form_fields() {
?>
<p class="form-row form-row-first">
<label for="billing_first_name"><?php _e('First name', 'text_domain'); ?><span class="required">*</span></label>
<input type="text" class="input-text" name="billing_first_name" id="billing_first_name" value="<?php if (!empty($_POST['billing_first_name'])) esc_attr_e($_POST['billing_first_name']); ?>" />
</p>
<p class="form-row form-row-last">
<label for="billing_last_name"><?php _e('Last name', 'text_domain'); ?><span class="required">*</span></label>
<input type="text" class="input-text" name="billing_last_name" id="billing_last_name" value="<?php if (!empty($_POST['billing_last_name'])) esc_attr_e($_POST['billing_last_name']); ?>" />
</p>
<div class="clear"></div>
<?php
}
add_action('woocommerce_register_form_start', 'text_domain_woo_reg_form_fields');
來到你的問題的第二部分驗證它是完全可選的,並且取決於你的業務邏輯,你想要什麼,一般來說大多數網站都需要名字和姓氏,但它又完全取決於你,如果你不想要驗證它,然後從上面的代碼中刪除<span class="required">*</span>
並跳過這一步 部分。
/**
* To validate WooCommerce registration form custom fields.
*/
function text_domain_woo_validate_reg_form_fields($username, $email, $validation_errors) {
if (isset($_POST['billing_first_name']) && empty($_POST['billing_first_name'])) {
$validation_errors->add('billing_first_name_error', __('<strong>Error</strong>: First name is required!', 'text_domain'));
}
if (isset($_POST['billing_last_name']) && empty($_POST['billing_last_name'])) {
$validation_errors->add('billing_last_name_error', __('<strong>Error</strong>: Last name is required!.', 'text_domain'));
}
return $validation_errors;
}
add_action('woocommerce_register_post', 'text_domain_woo_validate_reg_form_fields', 10, 3);
現在,這是一個主要組成部分,這一點,你是錯過了什麼,下面需要的代碼來保存自定義數據:
/**
* To save WooCommerce registration form custom fields.
*/
function text_domain_woo_save_reg_form_fields($customer_id) {
//First name field
if (isset($_POST['billing_first_name'])) {
update_user_meta($customer_id, 'first_name', sanitize_text_field($_POST['billing_first_name']));
update_user_meta($customer_id, 'billing_first_name', sanitize_text_field($_POST['billing_first_name']));
}
//Last name field
if (isset($_POST['billing_last_name'])) {
update_user_meta($customer_id, 'last_name', sanitize_text_field($_POST['billing_last_name']));
update_user_meta($customer_id, 'billing_last_name', sanitize_text_field($_POST['billing_last_name']));
}
}
add_action('woocommerce_created_customer', 'text_domain_woo_save_reg_form_fields');
以上所有的代碼都在function.php
文件的活躍兒童主題(或主題)。或者也可以在任何插件php文件中使用。
該代碼已經過測試並且功能齊全。
希望這有助於!