如何将WooCommerce自定义注册字段添加到WordPress后台用户联系人字段
完整解决方案
你之前仅声明了挂载钩子,缺少对应的字段渲染、数据读取以及编辑后的数据保存逻辑,完整实现代码如下:
// 在用户编辑页渲染自定义字段 function print_custom_fileds_in_edit_user( $user ) { // 读取已存储的用户扩展字段值 $billing_phone = get_user_meta( $user->ID, 'billing_phone', true ); $customer_dob = get_user_meta( $user->ID, 'customer_dob', true ); ?> <h3>用户扩展信息</h3> <table class="form-table"> <tr> <th><label for="customer_dob">出生日期</label></th> <td> <input type="text" name="customer_dob" id="customer_dob" value="<?php echo esc_attr( $customer_dob ); ?>" class="regular-text" /> </td> </tr> <tr> <th><label for="billing_phone">手机号</label></th> <td> <input type="text" name="billing_phone" id="billing_phone" value="<?php echo esc_attr( $billing_phone ); ?>" class="regular-text" /> </td> </tr> </table> <?php } // 管理员编辑其他用户页面钩子 add_action( 'edit_user_profile', 'print_custom_fileds_in_edit_user', 30 ); // 用户编辑个人资料页钩子,可按需添加 add_action( 'show_user_profile', 'print_custom_fileds_in_edit_user', 30 ); // 保存用户编辑页提交的自定义字段 function save_custom_user_profile_fields( $user_id ) { // 权限校验,仅允许有编辑用户权限的账号操作 if ( ! current_user_can( 'edit_user', $user_id ) ) { return false; } // 保存出生日期 if ( isset( $_POST['customer_dob'] ) ) { update_user_meta( $user_id, 'customer_dob', sanitize_text_field( $_POST['customer_dob'] ) ); } // 保存手机号 if ( isset( $_POST['billing_phone'] ) ) { update_user_meta( $user_id, 'billing_phone', sanitize_text_field( $_POST['billing_phone'] ) ); } } add_action( 'edit_user_profile_update', 'save_custom_user_profile_fields' ); add_action( 'personal_options_update', 'save_custom_user_profile_fields' );
将上述代码添加到主题functions.php文件或者自定义功能插件中即可生效,默认会在用户编辑页底部展示两个扩展字段,支持直接编辑保存。如果需要调整展示位置,修改add_action的第三个优先级参数即可,数值越小位置越靠前。
内容的提问来源于stack exchange,提问作者Siddharth
相关产品推荐
相关产品推荐

