I’m searching how to make First Name and Last name fields required when we add a new user. Right now only username and Email fields are required.
I found a way by adding class="form-required"
for the first and last name fields on the file user-new.php.
But I’m looking for a method with adding code on function.php and not touch to the WordPress Core.
Thanks.
If you were looking to make the fields required in the WordPress admin form for adding new user as i understood from your question, where the output is not filterable, you could basically do what you described (adding form-required) on browser side
function se372358_add_required_to_first_name_last_name(string $type) {
if ( 'add-new-user' === $type ) {
?>
<script type="text/javascript">
jQuery(function($) {
$('#first_name, #last_name')
.parents('tr')
.addClass('form-required')
.find('label')
.append(' <span class="description"><?php _e( '(required)' ); ?></span>');
});
</script>
<?php
}
return $type;
}
add_action('user_new_form', 'se372358_add_required_to_first_name_last_name');
Edit
In order to achieve the same on edit, you could use code like this:
function se372358_add_required_to_first_name_last_name_alternative() {
?>
<script type="text/javascript">
jQuery(function($) {
$('#createuser, #your-profile')
.find('#first_name, #last_name')
.parents('tr')
.addClass('form-required')
.find('label')
.append(' <span class="description"><?php _e( '(required)' ); ?></span>');
});
</script>
<?php
}
add_action('admin_print_scripts', 'se372358_add_required_to_first_name_last_name_alternative', 20);
function se372358_validate_first_name_last_name(WP_Error &$errors) {
if (!isset($_POST['first_name']) || empty($_POST['first_name'])) {
$errors->add( 'empty_first_name', __( '<strong>Error</strong>: Please enter first name.' ), array( 'form-field' => 'first_name' ) );
}
if (!isset($_POST['last_name']) || empty($_POST['last_name'])) {
$errors->add( 'empty_last_name', __( '<strong>Error</strong>: Please enter last name.' ), array( 'form-field' => 'last_name' ) );
}
return $errors;
}
add_action( 'user_profile_update_errors', 'se372358_validate_first_name_last_name' );