WooCommerce 我的账户注册表单中自定义生日字段的实现与保存教程

花韻仙語
发布: 2025-12-14 19:46:07
原创
862人浏览过

WooCommerce 我的账户注册表单中自定义生日字段的实现与保存教程

本教程详细指导如何在 woocommerce "我的账户" 注册表单中添加并正确保存自定义生日字段。文章涵盖了前端表单元素的生成、后端数据验证以及关键的数据格式化与保存逻辑,特别解决了多选下拉框(日、月、年)组合日期并存储为 `yyyy-mm-dd` 格式的常见问题,确保用户生日信息能被准确地录入和存储。

引言

在 WooCommerce 商店中,有时我们需要收集用户除默认信息之外的更多数据,例如生日。虽然 WooCommerce 默认的注册表单不包含生日字段,但通过 WordPress 提供的钩子(Hooks)机制,我们可以轻松地添加自定义字段并将其保存到用户元数据中。本教程将详细介绍如何利用 woocommerce_register_form_start、woocommerce_register_post 和 woocommerce_created_customer 这三个核心钩子,实现一个包含日、月、年三个下拉选择框的生日字段,并确保其数据能够被正确验证、格式化和保存。

1. 在注册表单中添加自定义生日字段

首先,我们需要在 WooCommerce 的注册表单中插入自定义的生日字段。我们将使用 woocommerce_register_form_start 动作钩子来在表单的开头部分添加这些字段。为了提供更好的用户体验,生日字段将由三个独立的

关键点: 月份的

/**
 * 在 "我的账户" 客户注册表单中添加自定义字段
 */
add_action( 'woocommerce_register_form_start', function() {
    ?>
    <p class="form-row form-row-first-name">
        <label for="billing_first_name"><?php _e( 'First name', 'woocommerce' ); ?><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-name">
        <label for="billing_last_name"><?php _e( 'Last name', 'woocommerce' ); ?><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>

    <table class="form-table">
        <tr>
            <th><label for="birth-date-day"><?php echo __( 'Birthday' ); ?></label></th>
            <td>
                <select id="birth-date-day" name="birthday[day]">
                    <option selected="selected" value=""><?php echo __( 'Day' ); ?></option><?php
                    for( $i = 1; $i <= 31; $i++ ) {
                        printf( '<option value="%1$s">%1$s</option>', $i );
                    } ?>
                </select>

                <select id="birth-date-month" name="birthday[month]">
                    <option selected="selected" value=""><?php echo __( 'Month' ); ?></option>
                    <option value="1"><?php _e( 'January' ); ?></option>
                    <option value="2"><?php _e( 'February' ); ?></option>
                    <option value="3"><?php _e( 'March' ); ?></option>
                    <option value="4"><?php _e( 'April' ); ?></option>
                    <option value="5"><?php _e( 'May' ); ?></option>
                    <option value="6"><?php _e( 'June' ); ?></option>
                    <option value="7"><?php _e( 'July' ); ?></option>
                    <option value="8"><?php _e( 'August' ); ?></option>
                    <option value="9"><?php _e( 'September' ); ?></option>
                    <option value="10"><?php _e( 'October' ); ?></option>
                    <option value="11"><?php _e( 'November' ); ?></option>
                    <option value="12"><?php _e( 'December' ); ?></option>
                </select>

                <select id="birth-date-year" name="birthday[year]">
                    <option selected="selected" value=""><?php echo __( 'Year' ); ?></option><?php
                    // 生成从当前年份-14到当前年份-99的年份选项
                    for( $i = date("Y") - 14; $i >= date("Y") - 99 ; $i-- ) {
                        printf( '<option value="%1$s">%1$s</option>', $i );
                    } ?>
                </select>
            </td>
        </tr>
    </table>
    <?php
} );
登录后复制

在上述代码中:

  • 我们为日、月、年分别创建了 select 标签,它们的 name 属性被设置为 birthday[day]、birthday[month] 和 birthday[year]。这将使它们在提交时作为一个关联数组 $_POST['birthday'] 传递。
  • 月份的
  • 年份选项从当前年份减去14年开始(假设最小注册年龄为14岁),到当前年份减去99年结束。

2. 验证自定义生日字段

为了确保用户提交了有效的生日信息,我们需要在表单提交时进行验证。woocommerce_register_post 钩子允许我们在用户数据保存之前添加自定义验证规则。

/**
 * 验证 "我的账户" 注册表单的自定义字段
 */
add_action( 'woocommerce_register_post', function( $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!', 'woocommerce' ) );
    }

    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!.', 'woocommerce' ) );
    }

    // 验证生日字段是否完整填写
    if( isset( $_POST['birthday'] ) ) {
        $birthday_data = $_POST['birthday'];
        if ( empty( $birthday_data['day'] ) || empty( $birthday_data['month'] ) || empty( $birthday_data['year'] ) ) {
            $validation_errors->add( 'birthday_error', __( '<strong>Error</strong>: Birthday is required!.', 'woocommerce' ) );
        }
    } else {
        $validation_errors->add( 'birthday_error', __( '<strong>Error</strong>: Birthday is required!.', 'woocommerce' ) );
    }

    return $validation_errors;
}, 10, 3 );
登录后复制

在验证逻辑中,我们检查 $_POST['birthday'] 数组中的 day、month 和 year 是否都已填写。如果任何一个为空,则添加一个错误信息。

Pippit AI
Pippit AI

CapCut推出的AI创意内容生成工具

Pippit AI 133
查看详情 Pippit AI

3. 保存自定义生日字段数据

用户注册成功后,我们需要将生日数据保存到用户的元数据中。woocommerce_created_customer 钩子在新用户创建后触发,并提供了新用户的 customer_id。

关键点: 正确地将日、月、年组合成一个 YYYY-MM-DD 格式的日期字符串,并使用 update_user_meta 函数进行保存。

/**
 * 保存 "我的账户" 注册表单的额外字段
 */
add_action( 'woocommerce_created_customer', function( $customer_id ) {
    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'] ) );
    }

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

    if( isset( $_POST['birthday'] ) ) {
        $birthday_data = $_POST['birthday'];
        // 确保日、月、年都有值
        if ( !empty($birthday_data['day']) && !empty($birthday_data['month']) && !empty($birthday_data['year']) ) {
            // 将数组转换为 '日-月-年' 格式的字符串,例如 '1-1-1990'
            $birthday_string = implode( '-', array( $birthday_data['day'], $birthday_data['month'], $birthday_data['year'] ) );

            // 使用 strtotime 解析字符串并格式化为 'Y-m-d' (yyyy-mm-dd)
            $birthday_formatted = date( 'Y-m-d', strtotime( $birthday_string ) );

            // 保存到用户元数据
            update_user_meta( $customer_id, 'birthday', $birthday_formatted );
        }
    }
} );
登录后复制

在保存逻辑中:

  • 我们首先从 $_POST['birthday'] 中获取日、月、年数据。
  • 使用 implode( '-', array( $birthday_data['day'], $birthday_data['month'], $birthday_data['year'] ) ) 将它们组合成一个如 "1-1-1990" 的日期字符串。这是关键的修正,因为原始代码尝试使用 implode(' ', ...) 后再 str_replace(' ', '', ...),这在月份没有数字 value 时会失败,并且 sanitize_text_field 直接作用于数组也是不正确的。
  • strtotime() 函数能够将这个格式的字符串解析为时间戳。
  • date( 'Y-m-d', ... ) 将时间戳格式化为标准的 YYYY-MM-DD 格式,便于数据库存储和后续处理。
  • 最后,使用 update_user_meta() 将格式化后的生日保存为用户的元数据。

完整实现代码

将以上所有代码片段合并,并放置在你的主题 functions.php 文件或一个自定义插件中,即可实现完整的自定义生日字段功能。

<?php
/**
 * 在 WooCommerce "我的账户" 客户注册表单中添加自定义生日字段并保存
 */

/**
 * 1. 在注册表单中添加自定义字段
 */
add_action( 'woocommerce_register_form_start', function() {
    ?>
    <p class="form-row form-row-first-name">
        <label for="billing_first_name"><?php _e( 'First name', 'woocommerce' ); ?><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-name">
        <label for="billing_last_name"><?php _e( 'Last name', 'woocommerce' ); ?><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>

    <table class="form-table">
        <tr>
            <th><label for="birth-date-day"><?php echo __( 'Birthday' ); ?></label></th>
            <td>
                <select id="birth-date-day" name="birthday[day]">
                    <option selected="selected" value=""><?php echo __( 'Day' ); ?></option><?php
                    for( $i = 1; $i <= 31; $i++ ) {
                        printf( '<option value="%1$s">%1$s</option>', $i );
                    } ?>
                </select>

                <select id="birth-date-month" name="birthday[month]">
                    <option selected="selected" value=""><?php echo __( 'Month' ); ?></option>
                    <option value="1"><?php _e( 'January' ); ?></option>
                    <option value="2"><?php _e( 'February' ); ?></option>
                    <option value="3"><?php _e( 'March' ); ?></option>
                    <option value="4"><?php _e( 'April' ); ?></option>
                    <option value="5"><?php _e( 'May' ); ?></option>
                    <option value="6"><?php _e( 'June' ); ?></option>
                    <option value="7"><?php _e( 'July' ); ?></option>
                    <option value="8"><?php _e( 'August' ); ?></option>
                    <option value="9"><?php _e( 'September' ); ?></option>
                    <option value="10"><?php _e( 'October' ); ?></option>
                    <option value="11"><?php _e( 'November' ); ?></option>
                    <option value="12"><?php _e( 'December' ); ?></option>
                </select>

                <select id="birth-date-year" name="birthday[year]">
                    <option selected="selected" value=""><?php echo __( 'Year' ); ?></option><?php
                    for( $i = date("Y") - 14; $i >= date("Y") - 99 ; $i-- ) {
                        printf( '<option value="%1$s">%1$s</option>', $i );
                    } ?>
                </select>
            </td>
        </tr>
    </table>
    <?php
} );

/**
 * 2. 验证 "我的账户" 注册表单的自定义字段
 */
add_action( 'woocommerce_register_post', function( $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!', 'woocommerce' ) );
    }

    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!.', 'woocommerce' ) );
    }

    if( isset( $_POST['birthday'] ) ) {
        $birthday_data = $_POST['birthday'];
        if ( empty( $birthday_data['day'] ) || empty( $birthday_data['month'] ) || empty( $birthday_data['year'] ) ) {
            $validation_errors->add( 'birthday_error', __( '<strong>Error</strong>: Birthday is required!.', 'woocommerce' ) );
        }
    } else {
        $validation_errors->add( 'birthday_error', __( '<strong>Error</strong>: Birthday is required!.', 'woocommerce' ) );
    }

    return $validation_errors;
}, 10, 3 );


/**
 * 3. 保存 "我的账户" 注册表单的额外字段
 */
add_action( 'woocommerce_created_customer', function( $customer_id ) {
    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'] ) );
    }

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

    if( isset( $_POST['birthday'] ) ) {
        $birthday_data = $_POST['birthday'];
        if ( !empty($birthday_data['day']) && !empty($birthday_data['month']) && !empty($birthday_data['year']) ) {
            $birthday_string = implode( '-', array( $birthday_data['day'], $birthday_data['month'], $birthday_data['year'] ) );
            $birthday_formatted = date( 'Y-m-d', strtotime( $birthday_string ) );
            update_user_meta( $customer_id, 'birthday', $birthday_formatted );
        }
    }
} );
登录后复制

注意事项与最佳实践

  1. 代码放置位置: 建议将上述代码放入你的主题 functions.php 文件中,或者创建一个自定义插件来管理这些功能。使用自定义插件是更好的实践,因为它与主题无关,即使更换主题也不会丢失功能。

以上就是WooCommerce 我的账户注册表单中自定义生日字段的实现与保存教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号