This Snippet is very easy. It ensures that only Administrators can have symbols apart from A to Z and 0-9 in their Author Names and Bios. Just add this code snippet to your functions.php file:
// Add validation for Author Name and Bio fields
add_action('user_profile_update_errors', 'validate_author_fields', 10, 3);
function validate_author_fields($errors, $update, $user) {
// Check if the user is not an administrator
if (!current_user_can('administrator', $user->ID)) {
// Validate the display_name (Author Name)
if (isset($_POST['display_name']) && !preg_match('/^[A-Z0-9]+$/i', $_POST['display_name'])) {
$errors->add('display_name_error', __('Only alphanumeric characters (A-Z, 0-9) are allowed in the Author Name for non-administrators.'));
}
// Validate the description (Bio)
if (isset($_POST['description']) && !preg_match('/^[A-Z0-9\s]+$/i', $_POST['description'])) {
$errors->add('description_error', __('Only alphanumeric characters (A-Z, 0-9) and spaces are allowed in the Bio for non-administrators.'));
}
}
}
// Save the validated fields
add_action('personal_options_update', 'save_author_fields');
add_action('edit_user_profile_update', 'save_author_fields');
function save_author_fields($user_id) {
// Ensure user has permission to edit
if (!current_user_can('edit_user', $user_id)) {
return false;
}
// Update user meta fields
if (isset($_POST['display_name'])) {
wp_update_user([
'ID' => $user_id,
'display_name' => sanitize_text_field($_POST['display_name']),
]);
}
if (isset($_POST['description'])) {
update_user_meta($user_id, 'description', sanitize_textarea_field($_POST['description']));
}
}
Leave a Reply