WordPress:为用户资料添加自定义单选框输入字段
如何将WordPress用户自定义文本字段改为单选按钮字段
直接给你修改好的代码,把原来的文本输入替换成了单选按钮组,同时完善了保存逻辑:
/***********************************************************/ /********** 自定义用户字段 ************/ /***********************************************************/ add_action( 'show_user_profile', 'extra_user_profile_fields' ); add_action( 'edit_user_profile', 'extra_user_profile_fields' ); function extra_user_profile_fields( $user ) { // 获取当前用户已保存的值 $selected_value = get_the_author_meta( 'equivalence_surcharge', $user->ID ); ?> <h3><?php _e("额外资料信息", "blank"); ?></h3> <table class="form-table"> <tr> <th><label><?php _e("等价附加费"); ?></label></th> <td> <!-- 单选按钮组,name必须一致才能互斥选择 --> <label> <input type="radio" name="equivalence_surcharge" value="yes" <?php checked( $selected_value, 'yes' ); ?> /> <?php _e("是"); ?> </label><br> <label> <input type="radio" name="equivalence_surcharge" value="no" <?php checked( $selected_value, 'no' ); ?> /> <?php _e("否"); ?> </label><br> <label> <input type="radio" name="equivalence_surcharge" value="custom" <?php checked( $selected_value, 'custom' ); ?> /> <?php _e("自定义"); ?> </label><br> <span class="description"><?php _e("请选择等价附加费状态"); ?></span> </td> </tr> </table> <?php } add_action( 'personal_options_update', 'save_extra_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' ); function save_extra_user_profile_fields( $user_id ) { if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-user_' . $user_id ) ) { return; } if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } // 处理单选按钮未选中的情况(比如用户没选任何选项时设默认值) $surcharge_value = isset( $_POST['equivalence_surcharge'] ) ? $_POST['equivalence_surcharge'] : 'no'; update_user_meta( $user_id, 'equivalence_surcharge', sanitize_text_field( $surcharge_value ) ); }
关键修改说明:
- 把原来的
<input type="text">替换成多个<input type="radio">,所有单选按钮的name属性必须相同,这样才能实现互斥选择 - 使用WordPress内置的
checked()函数自动判断当前用户的选中状态,简化代码逻辑 - 保存函数中增加了对
$_POST['equivalence_surcharge']的存在性检查,避免用户未选择任何选项时出现报错,同时设置默认值为no - 用
sanitize_text_field()对提交的值进行安全过滤,符合WordPress安全规范
内容的提问来源于stack exchange,提问作者JPashs
相关产品推荐
相关产品推荐

