Add a required custom field on admin new user form for a specific role in WordPress

120 Views Asked by At

I have added some user roles that have custom fields that can be filled when editing the user after creation but I want them to be assigned on user creation (Add New).

<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>
1

There are 1 best solutions below

0
LoicTheAztec On

To add user custom fields on user profile creation, you need to use user_new_form hook.

The following hooked function include your field code, with some modifications:

  • The "required" attribute option is not needed as it will be dynamically set when the correct user role will be selected.
  • When loading the page, the field will be hidden and will show when the desired user role will be selected.
  • This dynamic show/hide feature is enabled via some jQuery code.

The code example (define the desire user role at the beginning of the function):

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
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.