Using WordPress ‘pre_user_nicename’ PHP filter

‘pre_user_nicename’ is a WordPress filter that allows you to modify a user’s nicename before the user is created or updated. This filter can be useful for customizing the way user nicenames are generated or displayed.

Usage

To use this filter, you need to create a custom function and hook it to the ‘pre_user_nicename’ filter.

function your_custom_function( $user_nicename ) {
    // Your custom logic here
    return $modified_user_nicename;
}
add_filter( 'pre_user_nicename', 'your_custom_function' );

Parameters

  • $user_nicename (string)
    • The user’s nicename.

Examples

Make all user nicenames uppercase

function uppercase_nicename( $user_nicename ) {
    return strtoupper( $user_nicename );
}
add_filter( 'pre_user_nicename', 'uppercase_nicename' );

This code snippet converts all user nicenames to uppercase. When a new user is created or an existing user is updated, their nicename will be converted to uppercase letters.

Replace spaces with hyphens in user nicenames

function replace_spaces_with_hyphens( $user_nicename ) {
    return str_replace( ' ', '-', $user_nicename );
}
add_filter( 'pre_user_nicename', 'replace_spaces_with_hyphens' );

This code snippet replaces spaces in user nicenames with hyphens, allowing for cleaner URLs when referencing user profiles.

Add a prefix to user nicenames

function add_prefix_to_nicename( $user_nicename ) {
    $prefix = 'user-';
    return $prefix . $user_nicename;
}
add_filter( 'pre_user_nicename', 'add_prefix_to_nicename' );

This code snippet adds a prefix “user-” to all user nicenames, making it easier to identify user-generated content.

Remove special characters from user nicenames

function remove_special_chars( $user_nicename ) {
    return preg_replace( '/[^A-Za-z0-9-]/', '', $user_nicename );
}
add_filter( 'pre_user_nicename', 'remove_special_chars' );

This code snippet removes special characters from user nicenames, ensuring that only alphanumeric characters and hyphens are allowed.

Limit the length of user nicenames

function limit_nicename_length( $user_nicename ) {
    $max_length = 15;
    return substr( $user_nicename, 0, $max_length );
}
add_filter( 'pre_user_nicename', 'limit_nicename_length' );

This code snippet limits the length of user nicenames to a maximum of 15 characters. If a user’s nicename is longer than 15 characters, it will be truncated to fit within the limit.