‘pre_user_{$field} is a dynamic WordPress PHP filter a that allows you to modify the value of a user field in the ‘db’ context before it’s saved to the database.
This filter uses a dynamic hook name, which means you can apply it to various user fields, such as ‘user_login’, ‘user_email’, ‘first_name’, and so on.
Usage
function my_pre_user_field( $value ) { return 'John'; } add_filters( "pre_user_{$field}", "my_pre_user_field" );
Parameters
$field
: string (dynamic part of the hook name representing the prefixed user field being filtered)$value
: mixed (the value of the prefixed user field)
Examples
Sanitize user email
function sanitize_user_email( $email ) { return filter_var( $email, FILTER_SANITIZE_EMAIL ); } add_filter( 'pre_user_user_email', 'sanitize_user_email' );
This code snippet adds a filter to sanitize the user’s email address before saving it to the database.
Prevent spaces in user_login
function remove_spaces_from_user_login( $username ) { return str_replace( ' ', '', $username ); } add_filter( 'pre_user_user_login', 'remove_spaces_from_user_login' );
This code snippet removes spaces from the ‘user_login’ field before saving it to the database.
Capitalize first_name
function capitalize_first_name( $first_name ) { return ucfirst( strtolower( $first_name ) ); } add_filter( 'pre_user_first_name', 'capitalize_first_name' );
This code snippet capitalizes the first letter of the ‘first_name’ field before saving it to the database.
Set default display_name
function set_default_display_name( $display_name, $user_id ) { $user = get_userdata( $user_id ); return $user->first_name . ' ' . $user->last_name; } add_filter( 'pre_user_display_name', 'set_default_display_name', 10, 2 );
This code snippet sets the default ‘display_name’ to the user’s first and last name before saving it to the database.
Validate user_website
function validate_user_website( $website ) { return filter_var( $website, FILTER_VALIDATE_URL ) ? $website : ''; } add_filter( 'pre_user_user_url', 'validate_user_website' );
This code snippet validates the ‘user_url’ (user website) field before saving it to the database. If the URL is invalid, it saves an empty string instead.