這是另一個有用的 PHP 程式碼片段:讓我們在 WooCommerce My Account 頁面上新增 Biling First Name 和 Billing Last Name 到登錄檔單!
PHP 程式碼片段:新增第一個和最後一個名字給 WooCommerce 我的帳戶登錄檔單
/** * @snippet Add First & Last Name to My Account Register Form - WooCommerce * @sourcecode https://businessbloomer.com/?p=21974 * @author Rodolfo Melogli * @credits Claudio SM Web * @compatible WC 2.6.14, WP 4.7.2, PHP 5.5.9 */ /////////////////////////////// // 1. ADD FIELDS add_action( 'woocommerce_register_form_start', 'bbloomer_add_name_woo_account_registration' ); function bbloomer_add_name_woo_account_registration() { ?> <p class="form-row form-row-first"> <label for="reg_billing_first_name"><?php _e( 'First name', 'woocommerce' ); ?> <span class="required">*</span></label> <input type="text" class="input-text" name="billing_first_name" id="reg_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="reg_billing_last_name"><?php _e( 'Last name', 'woocommerce' ); ?> <span class="required">*</span></label> <input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" value="<?php if ( ! empty( $_POST['billing_last_name'] ) ) esc_attr_e( $_POST['billing_last_name'] ); ?>" /> </p> <div class="clear"></div> <?php } /////////////////////////////// // 2. VALIDATE FIELDS add_filter( 'woocommerce_registration_errors', 'bbloomer_validate_name_fields', 10, 3 ); function bbloomer_validate_name_fields( $errors, $username, $email ) { if ( isset( $_POST['billing_first_name'] ) && empty( $_POST['billing_first_name'] ) ) { $errors->add( 'billing_first_name_error', __( '<strong>Error</strong>: First name is required!', 'woocommerce' ) ); } if ( isset( $_POST['billing_last_name'] ) && empty( $_POST['billing_last_name'] ) ) { $errors->add( 'billing_last_name_error', __( '<strong>Error</strong>: Last name is required!.', 'woocommerce' ) ); } return $errors; } /////////////////////////////// // 3. SAVE FIELDS add_action( 'woocommerce_created_customer', 'bbloomer_save_name_fields' ); function bbloomer_save_name_fields( $customer_id ) { if ( isset( $_POST['billing_first_name'] ) ) { update_user_meta( $customer_id, 'billing_first_name', sanitize_text_field( $_POST['billing_first_name'] ) ); } if ( isset( $_POST['billing_last_name'] ) ) { update_user_meta( $customer_id, 'billing_last_name', sanitize_text_field( $_POST['billing_last_name'] ) ); } }
如何新增此程式碼?
1 、您可以將 PHP 程式碼片段放置在主題或子主題的 functions.php 檔案的底部 (如果是 CSS 程式碼,請新增到子主題的 style.css 檔案底部) 修改之前建議先備份原始檔案,若出現錯誤請先刪除此程式碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 程式碼也可開啟網站前臺編輯器的 【自定義】,複製程式碼新增到自定義 css 中。
此程式碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 使用者也希望您的參與。