‘pre_user_nickname’ allows you to modify a user’s nickname before it is saved during the user creation or update process in WordPress.
Usage
To use this filter, you need to add your custom function to it using add_filter()
:
add_filter('pre_user_nickname', 'your_custom_function', 10, 1); function your_custom_function( $nickname ) { // Your custom code here }
Parameters
- $nickname (string): The user’s nickname.
Examples
Capitalize First Letter of Nickname
function capitalize_first_letter($nickname) { return ucfirst($nickname); } add_filter('pre_user_nickname', 'capitalize_first_letter', 10, 1);
This example ensures that the first letter of the user’s nickname is always capitalized.
Replace Spaces with Hyphens
function replace_spaces_with_hyphens($nickname) { return str_replace(' ', '-', $nickname); } add_filter('pre_user_nickname', 'replace_spaces_with_hyphens', 10, 1);
This example replaces any spaces in the user’s nickname with hyphens.
Append User Role to Nickname
function append_user_role_to_nickname($nickname) { $user = wp_get_current_user(); $role = array_shift($user->roles); return $nickname . '_' . $role; } add_filter('pre_user_nickname', 'append_user_role_to_nickname', 10, 1);
This example appends the user’s role to their nickname.
Add Prefix to Nickname
function add_prefix_to_nickname($nickname) { return 'WP_' . $nickname; } add_filter('pre_user_nickname', 'add_prefix_to_nickname', 10, 1);
This example adds a “WP_” prefix to the user’s nickname.
Set Nickname to Email Local Part
function set_nickname_to_email_local_part($nickname) { $user = wp_get_current_user(); $email = $user->user_email; $local_part = substr($email, 0, strpos($email, '@')); return $local_part; } add_filter('pre_user_nickname', 'set_nickname_to_email_local_part', 10, 1);
This example sets the user’s nickname to the local part of their email address (the part before the @ symbol).