我添加了一些具有自定义字段的用户角色,可以在创建后编辑用户时填写这些字段,但我希望在创建用户时分配它们(添加新的)。
<tr>
<th><label for="area"><?php _e('Area', 'area'); ?></label></th>
<td>
<?php wp_dropdown_categories([
'name' => 'force_area',
'taxonomy' => 'area',
'show_option_none' => __('— Select —', 'pcc-paro'),
'option_none_value' => '0',
'selected' => $area ? $area->term_id : 0,
'required' => true,
]); ?>
</td>
</tr>
要在创建用户配置文件时添加用户自定义字段,您需要使用
user_new_form
钩子。
以下挂钩函数包含您的字段代码,并进行了一些修改:
代码示例(在函数开头定义所需的用户角色):
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' => __('— Select —', '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
}