Using WordPress ‘pre_user_display_name’ PHP filter

The ‘pre_user_display_name’ filter allows you to modify a user’s display name before the user is created or updated in WordPress.

Usage

To use this filter, create a function that accepts one parameter, $display_name, and add it to the pre_user_display_name filter using the add_filter() function.

function my_function( $display_name ) {
    // Your code to modify $display_name
    return $display_name;
}
add_filter( 'pre_user_display_name', 'my_function' );

Parameters

  • $display_name (string)
    • The user’s display name.

Examples

Capitalize display names

function capitalize_display_name( $display_name ) {
    return ucwords( strtolower( $display_name ) );
}
add_filter( 'pre_user_display_name', 'capitalize_display_name' );

This code snippet capitalizes the first letter of each word in the display name.

Add a prefix to display names

function add_prefix_to_display_name( $display_name ) {
    return 'WP_' . $display_name;
}
add_filter( 'pre_user_display_name', 'add_prefix_to_display_name' );

This code snippet adds “WP_” as a prefix to the display name.

Replace spaces with underscores

function replace_spaces_with_underscores( $display_name ) {
    return str_replace( ' ', '_', $display_name );
}
add_filter( 'pre_user_display_name', 'replace_spaces_with_underscores' );

This code snippet replaces spaces in the display name with underscores.

Add user role to display name

function add_user_role_to_display_name( $display_name ) {
    $user = wp_get_current_user();
    $user_role = $user->roles[0];
    return $display_name . ' (' . $user_role . ')';
}
add_filter( 'pre_user_display_name', 'add_user_role_to_display_name' );

This code snippet appends the user’s role to their display name in parentheses.

Remove numbers from display names

function remove_numbers_from_display_name( $display_name ) {
    return preg_replace( '/\d/', '', $display_name );
}
add_filter( 'pre_user_display_name', 'remove_numbers_from_display_name' );

This code snippet removes any numbers from the display name.