在管理员新用户表单上为 WordPress 中的特定角色添加必填自定义字段

问题描述 投票:0回答:1

我添加了一些具有自定义字段的用户角色,可以在创建后编辑用户时填写这些字段,但我希望在创建用户时分配它们(添加新的)。

<tr>
    <th><label for="area"><?php _e('Area', 'area'); ?></label></th>
    <td>
        <?php wp_dropdown_categories([
            'name' => 'force_area',
            'taxonomy' => 'area',
            'show_option_none' => __('&mdash; Select &mdash;', 'pcc-paro'),
            'option_none_value' => '0',
            'selected' => $area ? $area->term_id : 0,
            'required' => true,
        ]); ?>
    </td>
</tr>
php wordpress settings custom-fields usermetadata
1个回答
0
投票

要在创建用户配置文件时添加用户自定义字段,您需要使用

user_new_form
钩子。

以下挂钩函数包含您的字段代码,并进行了一些修改:

  • 不需要“必需”属性选项,因为当选择正确的用户角色时,它将动态设置。
  • 加载页面时,该字段将隐藏,并在选择所需的用户角色时显示。
  • 此动态显示/隐藏功能是通过一些 jQuery 代码启用的。

代码示例(在函数开头定义所需的用户角色):

add_action('user_new_form', 'show_extra_profile_field_on_user_creation');
function show_extra_profile_field_on_user_creation() {
    $role = 'author'; // <== HERE define the targeted user role
?>
<table class="form-table extra-custom-fields" style="display:none;">
    <tr>
    <th><label for="area"><?php _e('Area', 'area'); ?></label></th>
    <td>
        <?php wp_dropdown_categories([
            'name' => 'force_area',
            'taxonomy' => 'area',
            'show_option_none' => __('&mdash; Select &mdash;', 'pcc-paro'),
            'option_none_value' => '0',
        ]); ?>
    </td>
</tr>
</table>
<script>
jQuery(function($){
    $('#createuser').on('change', 'select[name=role]', function(){
        if( $(this).find('option:selected').val() === '<?php echo $role; ?>' ) {
            $('.extra-custom-fields').show();
            $('select[name=force_area]').attr('required', true);
        } else {
            $('.extra-custom-fields').hide();
            $('select[name=force_area]').removeAttr('required');
        }
    });
});
</script>
<?php
}
© www.soinside.com 2019 - 2024. All rights reserved.